0

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;

}
Attachments prog.jpg 28.28 KB
3
Contributors
3
Replies
7
Views
3 Years
Discussion Span
Last Post by ishaan3731
1

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.