Leonek
Leonek

Reputation: 31

Using Dynamic Memory Allocation for strings Arrays

I'm just starting to learn C, so if you can, please don't be so hard on me. I'm trying to learn how to allocate memory for arrays, so i started with someting like this. I just wanna dynamicly allocate memory for array of strings, and then display it.

int main( )
{
    int number, i;
    scanf ("%d", &number);
    char **table =(char **) malloc(number*sizeof(char*));
    for(i=0; i<number; i++)
    {
        table[i] = (char *)malloc(6);
    }

    for(i=0; i<number; i++)
    {
        scanf("%s", &table[i]);
    }

    for(i=0; i<number; i++)
    {
        printf("Person nr %d : %s ", i+1, &table[i]);
    }

    for(i=0; i<number; i++)
    {
         free(table[i]);
    }
    free(table);
    return 0;
}

But program only works when i type words with 3 or less letters. So, I don't know if i have a problem with memory allocation, or maybe i i just can't print with %s for **char? Maybe someone could tell me where I'm doing wrong and explain why?

Thank you for taking the time to read it :)

Upvotes: 0

Views: 77

Answers (2)

Shaw Song
Shaw Song

Reputation: 1

&table[i] is of the type char** and table[i] is the type char*. table[i] is the pointer for your string. You should change the &table[i] to table[i].

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

The problem is this:

scanf("%s", &table[i]);

and this:

printf("Person nr %d : %s ", i+1, &table[i]);

You seem to forget that table[i] is a pointer to char which is what a string basically is. By using &table[i] you get a pointer to the pointer, which is of type char **. You basically treat the pointer itself as a string, not the memory it points to.

Simply drop the address-of operator and you can read strings up to five characters (plus the terminator).

Upvotes: 4

Related Questions