为什么输出所说的可变大小可能无法初始化?

 char letM[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 int nr;
 printf("enter a number between 7 and 15\n");
 scanf("%d", &nr);
 for (int j = 0; j<=nr-5; j++){
   char letter[j] = letM[rand()%26+1];
   printf("%c", letter);
 }

此代码应为图章nr-5字母,但在我运行它时,输出会显示错误:可变大小的对象可能未初始化

评论
嘘!安静
嘘!安静

char letter[j]; defines letter to be an array containing j elements, each of which is a char. Because j is a variable, this is called a variable length array.

char letter[j] = letM[rand()%26+1]; defines such an array and attempts to initialize it with the value of letM[rand()%26+1];. The C standard does not provide for initializing variable length arrays. (They must be given values via ordinary assignments statements or other means, not via initializers in declarations.)

You may have meant to declare letter to be a single char. In this case, change the code to char letter = letM[rand()%26+1];.

点赞
评论
cet
cet

You have to declare what letter is before using it. Here's an option if you want to store the letters. Besides, when you print letter don't forget to print letter[j] instead.

     char letter[21];
     char letM[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     int nr;
     printf("enter a number between 7 and 15\n");
     scanf("%d", &nr);
     for (int j = 0; j<=nr-5; j++){
       letter[j] = letM[rand()%26+1];
       printf("%c", letter[j]);
     }

否则,就像其他建议一样,在这里,如果您只想打印字母,则甚至不需要变量:

 char letM[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 int nr;
 printf("enter a number between 7 and 15\n");
 scanf("%d", &nr);
 for (int j = 0; j<=nr-5; j++){
   printf("%c", letM[rand()%26+1]);
 }
点赞
评论