您好,我正在尝试编写一个程序,该程序将在运行时创建内存,这样该程序可以在生成内存以存储字符串时连续运行,直到用户决定退出。但是,当我运行该程序时,我可以正确输入字符串,但是将它们打印出来就是另一回事了。我认为问题是在循环中我覆盖了通过每次迭代创建的内存。这是我到目前为止所拥有的:
int main(){
char **lines = NULL;
char sentence[1000];
int numOfLines = 1;
int i;
int j;
printf("Enter the sentence:\n");
lines = (lines, numOfLines * sizeof *lines);
for (i=0; i <= numOfLines; i++){
fgets(sentence, 1000, stdin);
lines[i] = malloc (sizeof(char) * strlen(sentence) +1);
if (strcmp(sentence, ".\n") == 0){ //exits loops if entered string is "."
break;
}
strcpy(lines[i], sentence);
numOfLines++;
printf("%s", lines[i]); // attempt at a Debug statement
}
numOfLines = numOfLines - 1;
for (j = numOfLines; j>=0; j--){ //prints out the lines in reverse
printf("%s\n", lines[j]);
}
return 0;
}
我可能会补充一点,当用户退出循环时我会遇到段错误。
最佳答案
lines[i] = malloc (sizeof(char) * strlen(sentence + 1));
这是一个问题。应该是
lines[i] = malloc (sizeof(char) * strlen(sentence) + 1);
关于c - 在程序运行时分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41948563/