我试图对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