简体   繁体   English

如何在C语言中将字符串添加到字符串数组中

[英]How to add string to array of strings in C

So I am getting re-acquainted with C, and this one concept has me particularly stuck. 所以我正在重新认识C,这个概念让我特别困惑。

The goal is to create a dynamically allocated array of strings. 目标是创建一个动态分配的字符串数组。 I have this done, first creating a null array and allocating the appropriate amount of space for each string entered. 我已完成此操作,首先创建一个空数组并为输入的每个字符串分配适当的空间量。 The only problem is, when I try to actually add a string, I get a seg fault! 唯一的问题是,当我尝试实际添加一个字符串时,我得到一个seg错误! I can't figure out why, I have a hunch that it is from improper allocation as I can't see anything wrong with my strcpy function. 我无法弄清楚为什么,我有预感,这是因为我的strcpy函数没有看错。

I have looked exhaustively on this site for an answer, and I have found help, but can't quite close the deal. 我已经在这个网站上详尽地查看了答案,我找到了帮助,但无法完成交易。 Any help you can provide would be greatly appreciated! 您将提供的任何帮助将不胜感激!

#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 has no memory allocated to it. word没有分配给它的内存。 Your program in its current form is trampling over unallocated memory as users enter words into your program. 当用户在程序中输入单词时,您当前形式的程序会践踏未分配的内存。

You should guesstimate how large your input would be and allocate the input buffer like this: 您应该猜测输入的大小并分配输入缓冲区,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM