简体   繁体   English

为什么output说变长可能没有初始化?

[英]why the output said variable-sized may not be initialized?

 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);
 }

this code should be stamp nr-5 letter but when I run it, output say error: variable-sized object may not be initialized此代码应为 nr-5 字母,但当我运行它时,output 说错误:可变大小的 object 可能未初始化

char letter[j]; defines letter to be an array containing j elements, each of which is a char .letter定义为包含j个元素的数组,每个元素都是一个char Because j is a variable, this is called a variable length array .因为j是一个变量,所以这称为变长数组

char letter[j] = letM[rand()%26+1]; defines such an array and attempts to initialize it with the value of letM[rand()%26+1];定义这样一个数组并尝试用letM[rand()%26+1]; . . The C standard does not provide for initializing variable length arrays, and that is why you are getting an error message about it. C 标准不提供初始化可变长度 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 .您可能打算将letter声明为单个char In this case, change the code to char letter = letM[rand()%26+1];在这种情况下,将代码更改为char letter = letM[rand()%26+1]; . .

Additionally, letM[rand()%26+1] indexes the array incorrectly.此外, letM[rand()%26+1]不正确地索引数组。 In C, indices start with zero, so you should not add one.在 C 中,索引从零开始,因此您不应添加一。 Use letM[rand()%26] .使用letM[rand()%26]

You have to declare what letter is before using it.你必须在使用它之前声明它是什么letter Here's an option if you want to store the letters.如果您想存储字母,这里有一个选项。 Besides, when you print letter don't forget to print letter[j] instead.此外,当你打印letter时不要忘记打印letter[j]

     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]);
     }

Otherwise, as other suggested, here if you just want to print the letter, you don't even need a variable:否则,正如其他建议的那样,如果您只想打印字母,您甚至不需要变量:

 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]);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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