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

时间:2023-01-05 23:40:29

I have this int count[1]; this array gives me 3 Rab output! but it has only 2 capacity and i wondered why?!

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

 }

my Members.txt contains:

我的Members.txt包含:

3
Rebaz salimi 3840221821 09188888888
4
95120486525
95120482642

1 个解决方案

#1


2  

count is an array of integers which can hold only one element. You pass it to functions which required char * as arguments thus, causing undefined behaviour.

count是一个整数数组,只能包含一个元素。您将它传递给需要char *作为参数的函数,从而导致未定义的行为。

printf("%s",b.count);      // %s expects char * not int[]

Also here-

strncpy(b.count, str, 1);

You need to manually copy using loop or use sscanf() depending on your data.

您需要使用循环手动复制或使用sscanf(),具体取决于您的数据。

Edit :-

  fgets(str,2,myfile);
        if(sscanf(str, "%d", &b.count[0])==1){
               printf("%d\n", b.count[0]);
               i++;
    }       

read from file and store in b.count[0], check return of sscanf if successful then print it's value.

从文件中读取并存储在b.count [0]中,如果成功则检查sscanf的返回值然后打印它的值。

Also,

fgets(str,2,myfile);
      ^^^ str is int[] but fgets requires argument as char *. 

So str should be of type char *.

所以str应该是char *类型。

#1


2  

count is an array of integers which can hold only one element. You pass it to functions which required char * as arguments thus, causing undefined behaviour.

count是一个整数数组,只能包含一个元素。您将它传递给需要char *作为参数的函数,从而导致未定义的行为。

printf("%s",b.count);      // %s expects char * not int[]

Also here-

strncpy(b.count, str, 1);

You need to manually copy using loop or use sscanf() depending on your data.

您需要使用循环手动复制或使用sscanf(),具体取决于您的数据。

Edit :-

  fgets(str,2,myfile);
        if(sscanf(str, "%d", &b.count[0])==1){
               printf("%d\n", b.count[0]);
               i++;
    }       

read from file and store in b.count[0], check return of sscanf if successful then print it's value.

从文件中读取并存储在b.count [0]中,如果成功则检查sscanf的返回值然后打印它的值。

Also,

fgets(str,2,myfile);
      ^^^ str is int[] but fgets requires argument as char *. 

So str should be of type char *.

所以str应该是char *类型。