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. :)
ptr[i]=malloc(strlen(buff)+1); strncpy(ptr[i], buff, strlen(buff)+1);
i couldnt define end of string cause i didnt copy +1 elenete (\0). :D