繁体   English   中英

为什么此char Array(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM