c - 如何将字符串添加到C中的字符串数组

标签 c arrays string memory allocation

所以我重新认识了 C,这个概念让我特别困惑。

目标是创建一个动态分配的字符串数组。我这样做了,首先创建一个空数组并为输入的每个字符串分配适当的空间量。唯一的问题是,当我尝试实际添加一个字符串时,出现段错误!我不明白为什么,我有一种预感,这是由于分配不当造成的,因为我看不出我的 strcpy 函数有任何问题。

我已在此站点上详尽地寻找答案,并找到了帮助,但无法完全达成交易。如果您能提供任何帮助,我们将不胜感激!

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

int main()
{
  int count = 0; //array index counter
  char *word; //current word
  char **array = NULL;


  char *term = "q"; //termination character
  char *prnt = "print";

  while (strcmp(term, word) != 0)
{
  printf("Enter a string.  Enter q to end.  Enter print to print array\n");
  // fgets(word, sizeof(word), stdin); adds a newline character to the word.  wont work in this case
  scanf("%s", word);

  //printf("word: %s\nterm: %s\n",word, term);

  if (strcmp(term, word) == 0)
    {
    printf("Terminate\n");
    } 

  else if (strcmp(prnt, word) == 0)
  {
    printf("Enumerate\n");

    int i;

    for (i=0; i<count; i++)
    {
      printf("Slot %d: %s\n",i, array[i]);
    }

  }
  else
  {
    printf("String added to array\n");
    count++;
    array = (char**)realloc(array, (count+1)*sizeof(*array));
    array[count-1] = (char*)malloc(sizeof(word));
    strcpy(array[count-1], word);
  }

}

  return ;

}

最佳答案

word 没有分配给它的内存。当用户在您的程序中输入单词时,您当前形式的程序正在占用未分配的内存。

您应该估计您的输入有多大并像这样分配输入缓冲区:

char word[80];  // for 80 char max input per entry

关于c - 如何将字符串添加到C中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889757/

相关文章:

android - 使用 NDK 交叉编译,对 le32toh 和 be32toh 的 undefined reference

.net - 搜索字符串文字

c++ - VS2015 无法理解静态内联函数

arrays - 根据其他单元格中的值求和

arrays - 将具有不断变化的值确定的属性的对象添加到向量中

javascript - 在不知道对象数组格式的情况下从对象数组获取键值数组(Javascript)?

ruby - 在 Ruby 中找出字符串之间的区别

ios - 无法使用类型为 'String' 的参数列表调用类型为 '(CustomObject)' 的初始值设定项

c - C 中嵌套且可扩展的 for 循环

c - 为什么 sizeof(my_arr)[0] 编译并等于 sizeof(my_arr[0])?