我正在学习C编程,并且有一个将动态内存分配给数组的问题。
我正在尝试读取二进制文件(它包含ascii art,这是一个图像)。前两行分别包含宽度(100)和高度(48)。其次是ascii艺术。
void readDimension(FILE *inFile, int *width, int *height)
{
int i;
for (i = 0; i < 2; i++)
{
if (i == 0)
{
fscanf(inFile, "%d", width);
}
if (i == 1)
{
fscanf(inFile, "%d", height);
}
}
}
unsigned char *foo(char *filename, int *width, int *height)
{
// Inside Foo I must create dynamic array of char to store image data
// Recommendation is to used fread()
// Also account for the carriage return at the end of file
**I am stuck, in how to allocate array dynamically and read data into the same**
}
int main(int argc, char** argv)
{
FILE *inFile;
int width, height;
if (argc == 1)
{
printf("Please specify a file name.\n");
}
else if (argc == 2)
{
inFile = fopen(argv[1], "rb");
if (inFile != NULL)
{
readDimension(inFile, &width, &height);
foo(argv[1], &width, &height);
}
else
{
printf("Error: File Not Found %s", argv[1]);
}
}
printf("Width: %d\n", width);
printf("Height: %d\n", height);
}