c - 数组在一段时间后发生变化

标签 c

我正在尝试编写一个代码,该代码接收无限数量的名称作为输入,并打印输入的数量和名称。然而,似乎在 while 循环完成后,字符串数组中的每个位置都是“QUIT”,这是 while 循环的结束条件。如果有人能看出问题所在,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
      char Input_String[50]="bla";
      printf("Please enter list of names:"); 
      char** InputArr=(char**)malloc(1*sizeof(char**)); 
      int count=1; 
      fgets(Input_String,50,stdin); 
      if(strcmp(Input_String,"QUIT\n")) 
          InputArr[0]=Input_String; 
      printf("%s",InputArr[0]);    
      while(strcmp(Input_String,"QUIT\n")) 
      {                
          fgets(Input_String,50,stdin); 
          if(strcmp(Input_String,"QUIT\n")!=0) 
          { 
               count++; 
               InputArr= (char**)realloc(InputArr,(count)*sizeof(char*));                 
               InputArr[count-1]=Input_String; 
               printf("%s",InputArr[count-1]); 
          }
      }
      printf("There are %d names:\n",count); 
      int i; 
      for(i=0;i<count;i++) 
      {
          printf("%s",InputArr[i]);
      }
  }

最佳答案

在这一行

InputArr[count-1]=Input_String;

您正在将该字符串的地址写入每个数组元素。因此,当您完成后,它们都会指向您输入的最后一条消息,即 QUIT

我建议

InputArr[count-1]=strdup(Input_String);

但请记住稍后释放strdup分配的内存。

关于c - 数组在一段时间后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553117/

相关文章:

c - 点精度后 3 位 float

c - 当操作数是 C 中的指针时,编译器如何处理运算符 +

c - 如何使用自定义 shell 回显 $0

c - 函数名称和原型(prototype)中的斜线和点?

c - 如何使用 SIMD 计算字符出现次数

c - 在 C 中打印和填充二维数组

c - 为什么我的进程没有同时运行?

为 MinGW 编译 glew32s.lib?

c - 函数 C 错误、类型不兼容和段错误核心转储

c - 为什么要在调用 fork() 之后和调用 exec...() 之前关闭所有文件描述符?我该怎么做?