动态分配指针数组

时间:2017-01-06 13:19:41

标签: c arrays pointers dynamic-allocation

我的C代码有问题。 我需要输入一个用enter按钮分隔的名字列表。 当用户输入单词“QUIT”时,输入停止。 程序需要按字母顺序打印名称列表(所有字母均为小写)。

名称数量以及每个名称的长度未知,需要动态分配。此外,如果名称在输入中出现多次,则它只应在输出中出现一次。

这是代码运行方式的示例:

Please enter a list of names:

john

chris

ben

chris

david

QUIT

有4个名字:

ben

chris

david

john

我考虑过使用动态分配的指针数组,其中每个指针都包含每个名称并且是动态分配的。问题是我不知道如何编写它而不会出现运行时错误。

注意:此时,我不允许使用我尚未学过的东西,比如结构和递归,并且只能使用库stdio.h,stdlib.h和string.h。

提前致谢。

这是代码(它不完整,但此时我收到运行时错误):

char **nameList;
int i = 0, j = 0, size = 0, check = 0;
printf("Please enter list of names:\n");
//allocate one cell of memory to the list
nameList = (char**)malloc(sizeof(char));
if (nameList == NULL)
{
    printf("Cannot allocate Memory");
    return 0;
}
//Add the first letter to the first string in the array
nameList[i][j] = getchar();
size += sizeof(char);
while (check != 1)
{
    //check if current entered letter is not an enter
    while (nameList[i][j] != '\n')
    {
        //allocated another char sized memory to the string
        nameList = (char**)realloc(nameList, (size + sizeof(char)));
        if (nameList == NULL)
        {
            printf("Cannot allocate Memory");
            return 0;
        }
        j++;
        //adding another char to the current string
        nameList[i][j] = getchar();
        size += sizeof(char);
    }
    j = 0;
    if (nameList[i][j] == 'Q')
    {
        if (nameList[i][j + 1] == 'U')
            if (nameList[i][j + 2] == 'I')
                if (nameList[i][j + 3] == 'T')
                    check++;
    }
    i++;
}

1 个答案:

答案 0 :(得分:0)

  

nameList =(char **)realloc(nameList,(size + sizeof(char)));

嗯......你为什么在那里使用'+'?而且你正在寻找错误价值的大小。

这会分配一个指针数组。但是指向这里的指针是什么?

相关问题