簡體   English   中英

如何在C語言中將字符串添加到字符串數組中

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

所以我正在重新認識C,這個概念讓我特別困惑。

目標是創建一個動態分配的字符串數組。 我已完成此操作,首先創建一個空數組並為輸入的每個字符串分配適當的空間量。 唯一的問題是,當我嘗試實際添加一個字符串時,我得到一個seg錯誤! 我無法弄清楚為什么,我有預感,這是因為我的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM