I'm trying to create a program which takes in a set number of strings (the user is asked to put in the number of strings they will enter), once it has these strings, they are placed in an array, using dynamic memory.
The ouput would be something like this:
# of Strings: 3
Cat
Dog
Elephant
Cat
Dog
Elephant
Heres a snippet of my code, after I have the number of strings.
sptr=malloc(sizeof(char*)*nStrings);
for(i=0;i<nStrings;i++)
{
scanf("%s",string);
length=strlen(string);
sptr[i]=malloc(sizeof(char)*length);
sptr[i]=string;
}
Where sptr is the array I'll access to output the strings. So it's an array of pointers which then point to individual strings (or other arrays of characters, if you'd prefer to think of it that way).
Lets say there are two strings. I allocate memory for two pointers, Then in the first pointer, i scan in a string, i find the length of the string, i allocate memory the size of the string and i equal the pointer to the string. This all works dandy, and if I were to put a printf() right after that last line, it will work. The problem i face is, if lets say there are 3 strings, each time through sptr[i] is assigned correctly, but then outside of that block, all of the indicies of sptr are = to the last string i put in, and I have no idea why.
If you could help me out I'd appreciate it. Thanks.