gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:22:47 26 4
gpt4 key购买 nike

所以我重新认识了 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com