我試圖對fwrite()
動態數組寫一個函數。 問題是fopen()
內的指針。C - 通過函數動態數組寫指針,指針
雖然成功fwrite()
動態數組文件,從主函數,當試圖移動fwrite()
到一個單獨的函數與指針發生麻煩。具體指向數組的指針,它們位於函數內的fwrite()
之內。
這裏是相關的代碼。
main()
{
...
unsigned char **pixels_array = NULL; //write this array to file
allocateArray(&pixels_array); //prepare array
fillArray(&pixels_array);
writeFile(&pixels_array);
freeArray(&pixels_array);
...
}
writeFile(unsigned char ***pixels_array) //param is pointer to double pointer array
{
...
FILE *file = fopen(output_filename, "wb"); //open file
if (file == NULL)
{
printf(ERROR_OPEN_FILE_MSG);
return ERROR_OPEN_FILE;
}
for(i = 0; i < height; i++) //writing row by row of the array to file
{
//PROBLEM
//seg fault when running with current pointers to pixels_array in fwrite()
fwrite((&(*(*pixels_array)))[i], sizeof(unsigned char) * padded_width, 1, file);
}
fclose(file);
}
allocateArray(unsigned char ***pixels_array)
{
...
*pixels_array = (unsigned char**)malloc(height * sizeof(unsigned char*)); //image y coord.
...
for(i = 0; i < height; i++)
{
//(allocate scanlines) image x coord., no sizeof(unsigned char*) because == 1
(*pixels_array)[i] = (unsigned char*)malloc(width);
...
}
...
}
爲什麼你不得不使用'(&(*(* pixels_array)))[i]'這個複雜的序列?不能變得更簡單,更直接? – 2014-12-03 07:11:44
由於im限於c89標準,這種解決方案似乎是合適的。分配的指針數組用於存儲圖像的像素。圖像大小是可變的。 – 2014-12-03 07:30:05
自從'c89'問你寫簡單工作的複雜陳述?你不能使用'pixels_array [i]'來代替嗎? – 2014-12-03 07:32:01