指针用作函数形参时,注意如果指针是在函数内申请内存,务必添加引用符号。这主要是因为在函数外指针是一个空指针,其指向未定。
int ReadData16U(const char *filename, Image16U *&image, int imgSize, HeadInfo &headInfo)
{
//16位无符号型[0,65535]
FILE* pFile = fopen(filename, "rb+");
if (pFile == NULL)
{
printf("ERROR: File %s does not exist\n", filename);
return -1;
}
int offset = sizeof(HeadInfo);
image = new Image16U[imgSize];
fread(&headInfo, 1, offset, pFile);
cout << headInfo.height << endl;
fread(image, imgSize * sizeof(Image16U), 1, pFile);
fclose(pFile);
return 1;
}
int test()
{
int w = 512, h = 512;
int chnl = 1;
char *filename = "test.dat";
Image16U *srcImage = nullptr;
HeadInfo headInfo;
ReadData16U(filename, srcImage, w*h, headInfo);
}
反之,如果指针是在函数外申请内存,则不需要引用符号。
int ReadData16U(const char *filename, Image16U *image, int imgSize, HeadInfo &headInfo)
{
//16位无符号型[0,65535]
FILE* pFile = fopen(filename, "rb+");
if (pFile == NULL)
{
printf("ERROR: File %s does not exist\n", filename);
return -1;
}
int offset = sizeof(HeadInfo);
fread(&headInfo, 1, offset, pFile);
cout << headInfo.height << endl;
fread(image, imgSize * sizeof(Image16U), 1, pFile);
fclose(pFile);
return 1;
}
int test()
{
int w = 512, h = 512;
int chnl = 1;
char *filename = "test.dat";
Image16U *srcImage = nullptr;
srcImage = new Image16U[w*h*chnl];
HeadInfo headInfo;
ReadData16U(filename, srcImage, w*h, headInfo);
}