【发布时间】: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