【发布时间】:2021-10-04 12:42:10
【问题描述】:
这是我的代码
int wordSize = 8; // defining a word size
int *myArray = NULL;
myArray = malloc(sizeof(char)*(wordSize+1)); // using malloc() so I always have a big enough array should wordSize change. Also to practice.
int index = 0; // defining a variable to browse through myArray
do
{
myArray[index] = '*';
index++;
}
while(index < wordSize);
myArray[wordSize] = '\0'; // filling myArray with '*' character and the null terminator /0
printf("%s", myArray); // trying to display myArray, only a single '*' is printed
printf("\n\n");
int i=0;
while(i < wordSize+1)
{
printf("%c", myArray[i]);
i++;
} // trying to display myArray with an other method, this time with success
自从
char string[] = "hello";
printf("%s", string);
工作得很好,我不明白为什么printf("%s", myArray); 不工作,只显示一个*。 do/while 循环按预期显示 8 *,这意味着我的数组已按应有的方式填充。
编辑:按照 cmets 的要求,简化了我的示例,并尝试了一些解决方案和其他一些可能性。
【问题讨论】:
-
*displayedSecretWord[characterCount] = '\0';是错误的,因为它试图访问索引为characterCount的元素,但malloc(sizeof(int)*characterCount);只为从0 到characterCount−1 的索引分配了足够的内存。除此之外,编辑问题以提供minimal reproducible example。 -
"This is because when my basic game will be working I want to be able to randomly choose from a list of words, so I can't have a fixed array."-- 你可以有一个强制的最大字长,然后你也可以有一个固定大小的数组。但是,如果您愿意,当然也可以使用malloc。 -
如果你想要一个字符数组,那你为什么要创建一个整数数组呢?每次增加指针时,它都会移动 4 个字节(sizeof int),因此您跳过了 3 个字符。