【问题标题】:How to add string to array of strings in C如何将字符串添加到C中的字符串数组
【发布时间】:2015-03-09 11:56:09
【问题描述】:

所以我重新熟悉了 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 ;

}

【问题讨论】:

    标签: c arrays string memory allocation


    【解决方案1】:

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

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

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

    【讨论】:

    • 啊!!我多么愚蠢,似乎总是忽略了微小的细节。这个固定帮助就像一个魅力。非常感谢!
    • 另外,在 OP 的代码中注释掉的 fgets(word, sizeof(word), stdin); 是错误的,因为 sizeof 运算符不计算 word 的字符数,而是返回 word 变量的大小类型,并且由于 word 是指针sizeof(word) 将给出指针的大小,即sizeof(char *)。但是,如果 OP 使用此解决方案,sizeof 运算符在这种情况下非常适用。
    • @colinmcp 哦,另外,防止缓冲区溢出 scanf("%79s", word); 该数字是数组的大小减 1,因为您应该考虑空终止字节。
    • @iharob 感谢您的提示,我最初将其注释掉是因为它提供了不必要的换行符,但很高兴知道这一点。
    • 另请注意,在第一次迭代中,您的while 条件是将term 与未初始化的字符串进行比较。声明 char word[80] = "" 应该可以解决这个问题,或者您可以重新设计主循环(例如,使用无限循环并在终止测试中将其中断以避免测试终止条件两次)。
    猜你喜欢
    • 2021-12-30
    • 2023-01-19
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多