c - 在程序运行时分配内存

标签 c loops memory malloc

您好,我正在尝试编写一个程序,该程序将在运行时创建内存,这样该程序可以在生成内存以存储字符串时连续运行,直到用户决定退出。但是,当我运行该程序时,我可以正确输入字符串,但是将它们打印出来就是另一回事了。我认为问题是在循环中我覆盖了通过每次迭代创建的内存。这是我到目前为止所拥有的:

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/

相关文章:

python - OpenMP中有没有类似Python的threading.Event的机制?

java - 我的递归方法无法正确返回 char 出现的总数

c++ - 高效的索引绑定(bind)检查和 double to int cast

MATLAB 中的 Java 堆大小问题

将字符映射表从主机内存复制到 CUDA 中的设备

大对象集的Java内存分配

c++ - 如何创建继承自 Release 的 CMake 配置类型

c - 函数参数匿名结构

c - 在socket中,如果我们在socket()中将SOCK_STREAM作为第二个参数,将UDP作为第三个参数,会发生什么?

Java while循环及其他