从不兼容的指针类型中传递参数x'y'
问题描述:
这是一个程序,主要是为了在尝试在较大的程序中使用它之前获得fopen和类似语法的挂起。所以程序试图完成的唯一事情就是打开一个文件(scores.dat),读取该文件中的数据,将其分配给一个数组,然后打印该数组。从不兼容的指针类型中传递参数x'y'
这是代码段的,我有一个错误:
int scores[13][4];
FILE *score;
score = fopen("scores.dat", "r");
fscanf("%d %d %d %d", &scores[0][0], &scores[0][1], &scores[0][2], &scores[0][3]);
printf("%d &d %d %d", scores[0][0], scores[0][1], scores[0][2], scores[0][3]);
fclose(score);
编译时,我得到的错误:
text.c: In function 'main':
text.c:15: warning: passing argument 1 of 'fscanf' from incompatible pointer type
text.c:15: warning: passing argument 2 of 'fscanf' from incompatible pointer type
我将如何解决呢?
在情况下,它是很重要的,scores.dat看起来是这样的:
88 77 85 91 65 72 84 96 50 76 67 89 70 80 90 99 42 65 66 72 80 82 85 83 90 89 93
98 86 76 85 99 99 99 99 99 84 72 60 66 50 31 20 10 90 95 91 10 99 91 85 80
答
你错过的fscanf()
第一个参数:
fscanf(score, "%d %d %d %d", &scores[0][0], ... etc.
^^^^^
this needs to be a `FILE *`, and not `const char *`.
答
你忘了提档:
fscanf(score, "%d %d %d %d", &scores[0][0], ...);
// ^^^^^
答
您对fopen()
的理解很好,因为您已经使用它了rrectly.But你已经通过了fscanf()
不其prototype.Here的原型匹配的参数:
int fscanf (FILE *, const char * , ...);
所以,你应该使用:
fscanf(source,"%d %d %d %d", &scores[0][0], &scores[0][1], &scores[0][2], &scores[0][3]);
一件事约fopen()
。在使用fopen()
打开文件时出现错误,然后退出程序时,包含一些显示消息的代码是谨慎的。喜欢的东西:
if(source==NULL)
{
printf("Error opening file");
exit(1);
}
而且因为'FILE *分数;'是一个指针,他可能会需要使用: '的fscanf(得分, “%d%d%d%d”,得分[0] [ 0],... etc.' – 2013-04-22 21:57:34
@MehdiKaramosly为什么?'fscanf()'修改它的参数。你当然不明白它是如何工作的(以及指针如何工作)。 – 2013-04-22 22:18:02
很长时间我没有操作指针的地址......我知道,即使矩阵的元素在内存中放置成一个,所以你可以通过很多方式访问地址:// // score + i * j * sizeof(int);' – 2013-04-22 23:38:07