2015-01-11 179 views
6

因此,我重新熟悉了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 ; 

} 

回答

6

word没有分配给它的存储器。当前用户的程序正在践踏未分配的内存,因为用户在程序中输入了单词。

你应该推测将会你的投入将有多大,并分配输入缓冲区这样的:

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

啊!我多么愚蠢,似乎总是被忽视的细节。这固定帮助像魅力。非常感谢! – colinmcp

+0

另外,'fgets(word,sizeof(word),stdin);'在OP代码中注释掉'是错误的,因为'sizeof'运算符不会计算'word'的字符数,而是返回'word'变量的类型,并且由于单词是指针'sizeof(word)'将给出指针的大小,即'sizeof(char *)'。如果OP使用这种解决方案,那么在这种情况下'sizeof'运算符就很适用。 –

+2

@colinmcp呵呵,还要防止缓冲区溢出做'scanf(“%79s”,word);'这个数字是数组的大小减1,因为你应该考虑空终止字节。 –