如何解决指向结构的指针
我已经编写了这段代码,其中readData接受输入并将值存储在结构中,而writeData打印这些值。 我需要结构Color *指针值保留在堆内存中,以便可以从writeData函数访问它。由于某种原因,它会在调用writeData时保留垃圾值。有人可以帮我弄清楚为什么会这样。谢谢
imageloader.c文件:
typedef struct Color
{
uint8_t R;
uint8_t G;
uint8_t B;
} Color;
typedef struct Image
{
Color **image;
uint32_t rows;
uint32_t cols;
} Image;
Image *readData(char *filename)
{
FILE *fp = fopen(filename,"r");
char format[3];
int rows = 0,cols = 0,num = 0;
uint8_t R_int = 0;
uint8_t G_int = 0;
uint8_t B_int = 0;
fscanf(fp,"%s\n %d \n %d\n",format,&rows,&cols,&num);
Color** p = (Color** )malloc(rows *cols * sizeof(Color*));
for(int i =0; i< rows *cols; i++)
{
fscanf(fp,"%d %d %d",&R_int,&G_int,&G_int);
Color* c = (Color *) malloc(sizeof(Color));
c->R = R_int;
c->G = G_int;
c->B = B_int;
p[i] = &c;
}
Image *img = (Image*)malloc(sizeof(Image));
img->image = p;
img->rows = rows;
img->cols = cols;
printf("%d",p[0]->R); //garbage value
return img;
}
void writeData(Image *image)
{
}
}
主函数调用readData和writeData
int main(int argc,char **argv)
{
Image *image;
uint32_t rule;
char *filename;
processCLI(argc,argv,&filename);
image = readData(filename);
writeData(image);
freeImage(image);
}
解决方法
打开编译器警告将帮助您查找此类错误。
$ clang -c -Wall -Wextra main.c
main.c:29:57: warning: data argument not used by format
string [-Wformat-extra-args]
..."%s\n %d \n %d\n",format,&rows,&cols,&num);
~~~~~~~~~~~~~~~~~ ^
main.c:33:32: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp,"%d %d %d",&R_int,&G_int,&G_int);
~~ ^~~~~~
%s
main.c:33:40: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp,&G_int);
~~ ^~~~~~
%s
main.c:33:48: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp,&G_int);
~~ ^~~~~~
%s
main.c:38:14: warning: incompatible pointer types assigning
to 'Color *' (aka 'struct Color *') from 'Color **'
(aka 'struct Color **'); remove &
[-Wincompatible-pointer-types]
p[i] = &c;
^ ~~
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。