![](/img/trans.png)
[英]Why can't i declare a more than three digits array of array of char in C?
[英]Why this char Array(C language) prints more than its capacity?
我有这个int count[1];
这个数组给了我3 Rab
输出! 但是它只有2个容量,我想知道为什么吗?
struct MEMBERS
{
int code;
char Fname[40];
char Lname[40];
int Pnum[20];
float bedeh;
float credit;
int count[1];
struct meroDate issued;
struct meroDate duedate;
};
struct MEMBERS b;
int main()
{
int i = 0, line = 5;
char w[100];
int str[100];
FILE *myfile;
myfile = fopen("Members.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fgets(str,2,myfile);
strncpy(b.count, str, 1);
i++;
printf("%s",b.count);
}
fclose(myfile);
return 0;
}
我的Members.txt
包含:
3
Rebaz salimi 3840221821 09188888888
4
95120486525
95120482642
count
是只能容纳一个元素的整数数组。 您将其传递给需要char *
作为参数的函数,从而导致未定义的行为。
printf("%s",b.count); // %s expects char * not int[]
也在这里-
strncpy(b.count, str, 1);
您需要使用循环来手动复制或根据数据使用sscanf()
。
编辑:-
fgets(str,2,myfile);
if(sscanf(str, "%d", &b.count[0])==1){
printf("%d\n", b.count[0]);
i++;
}
从文件中读取并存储在b.count[0]
,检查sscanf
返回是否成功,然后打印其值。
也,
fgets(str,2,myfile);
^^^ str is int[] but fgets requires argument as char *.
所以str
应该是char *
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.