BugShotGG
BugShotGG

Reputation: 5190

pointer array with strings using malloc and buffer in C

I am stuck in how to fill a pointer array with strings using malloc. In debug i see that when i fill the 1st pointer of array with a string, when its about to go to next pointer in the array it pass the next string in both 1st and second element... seems like when i use ptr[i]=buff; the ptr keeps showing in the buff array.

    #include<stdlib.h>
    #include<string.h>
    #define size 2       //array of 2 pointers
    int main()
{
    int i;
    char *ptr[size];
    char buff[80];

    for (i=0;i<size;i++)
    {
        memset(buff, 0, sizeof(char) * 80);
        printf("Enter name:\n");fflush(stdout);
        scanf("%s",buff);

        ptr[i]=(char*)malloc(strlen(buff));
        //ptr[i]=buff;                        //that was the mistake
        strncpy(ptr[i], buff, strlen(buff));    //->correct answer!
        printf("length %d\n",strlen(buff));
    }
    for (i=0;i<size;i++)
    {
        printf("prt[%d]=%s\n",i,ptr[i]);fflush(stdout);
    }
    for (i=0;i<size;i++)
    {
        free(ptr[i]);
    }
    return 0;
}

Another weird question that i have has to do with the length of the arrays in general. When an array is declared for example a[10] the pointer a points to the first element of the array. What i do not understand is where the length is being stored!? is it the previous memory address of the pointer a? Is it before? Or does it have to do with the compiler only? Thanks. i hope that wasnt too much i asked. :)

Upvotes: 0

Views: 3321

Answers (2)

NPE
NPE

Reputation: 500307

The following is incorrect:

ptr[i]=buff

You should use strcpy() instead of the assignment.

Otherwise you assign the same pointer to all elements of ptr, leak the malloc()ed memory, and try to free() things you haven't malloc()ed.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

This:

ptr[i]=buff;

does not copy the string. It just copies a pointer. So not have you caused a memory leak (you have no way to access the memory you just allocated), but it messes your program up, because ptr[i] now points at buff, so every time you read a new string, it will appear to affect all elements of ptr[].

Do this instead:

strncpy(ptr[i], buff, BUF_SIZE);

Note also that it's considered bad practice to use gets; consider what would happen if the user were to type a string with more than 9 characters.

Upvotes: 4

Related Questions