Dynamic allocation of an array of pointers

369 views Asked by At

I have a problem with a code in C. I need to enter a list of names separated with the enter button. The input is stopped when the user enters the word "QUIT". the program needs to print the list of names in an alphabetical order (all letters are lowercase).

The number of names as well as the length of each name is unknown, and needs to be dynamic allocated. Also, if a name appears more than once in the input, it should appear only once in the output.

here's an example for how the code should run:

Please enter a list of names:

john

chris

ben

chris

david

QUIT

There are 4 names:

ben

chris

david

john

I thought about using a dynamic allocated array of pointers, in which each pointer contains each name and is dynamic allocated. The problem is that I don't know how to write it without getting a run-time error.

Note: at this point, I am not allowed to use things that I haven't learned yet, like structs and recursion, and can only use the libraries stdio.h, stdlib.h and string.h.

Thanks in advance.

here's the code (it's not complete, but I'm getting a runtime error at this point):

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

There are 1 answers

3
luckykaa On

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

Uhm... Why are you using a '+' there? And you are looking for the size of the wrong sort of value as well.

This allocates an array of pointers. But what are the pointers pointing to here?