i have this code which tries to enter data into an array of string(char ptr) called token.To do this i have used a while loop to obtain a string as user input and put that string into the token array one by one. But when i try to print the token array outside while loop all the token array elements are equal to the last user entered element in while loop.

Output : the screenshot of output is attached in the post.

#include<stdio.h>
#include<string.h>
#include<conio.h>

int main(int argc, char **argv)
{   int i=0,j=0;
    char *token[20];
    char buff[20];
    while(i<5)
    {
    printf("\nenter value :");
    gets(buff);
    token[i]=buff;
    i++;
    }

  for(j=0;j<5;j++)
{
    printf("\n%s",token[j]);
}
return 0;

}

That is because you only have 1 buffer, buff. At line 13 all you do is store a pointer to buff in the array token so all entries in token end up pointing an the same buffer, buff and when you print out your tokens they all contain the same thing, the last thing you entered, because they are literally pointing at the same object.

change the declaration of token to char token[20][20]; and strcpy from buff into token (or just get rid of buff altogether.

Or change line 13 to this so that token has a pointer to unique memory:

token[i]=strdup(buff);

thanks to all for helping me!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.