为什么这个char数组(C语言)打印的容量超过其容量?

时间:2017-06-18 17:08:10

标签: c arrays file-io

我有这个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

1 个答案:

答案 0 :(得分:2)

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 *类型。

相关问题