Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

taking Strings into Array.

Status
Not open for further replies.

logic4fun

Programmer
Apr 24, 2003
85
US
Hi all,
I am confused..whether i am trying which we cant do or I am doing wrong..I would say i am doing some mistake in the following chunk. all i wanted to do is take a bunch of strings into a string pointer array so that i can reuse them.
**********************************
char i[35];
char *j[5];

memset(i,0,sizeof(i));
for (lt=0;lt < 3; lt++) {

if(m==0)
strcpy(i, &quot;Hello&quot;);
if(m==1)
strcpy(i, &quot;Hi there&quot;);
if(m==2)
strcpy(i,&quot;How r ya&quot;);

j[lt]=i;
printf(&quot;i - %s, lt - %d, j - %s\n&quot;,i,lt,j[lt]);
m++;
}
printf(&quot;Value of j[0] j[1] j[2] is :%s %s %s \n&quot;,j[0],j[1],j[2]);
************************

The above chunk always gives me the last string. for all the three locations.
it prints
How r ya How r ya How r ya


but i need
Hello Hi there how r ya

All i need to do is make a pointer array of those three strings..I proceeded the above way by seeing the example of Tokenizing using strtok where we take all tokens into array of pointers..

Thanks in advance
logic4fun
 
> j[lt]=i;
This doesn't make a copy of the string, it just makes a pointer to the string. Since the pointer is a constant (it's an array), everything ends up pointing at the same block of memory.

> printf(&quot;Value of j[0] j[1] j[2] is :%s %s %s \n&quot;,j[0],j[1],j[2]);
Replace those %s with %p, and you'll see that all the j array elements are all pointing at the i array
Especially if you also do
Code:
printf(&quot;%p\n&quot;, i );

The fix (1)
Code:
char j[5][35];
...
      strcpy(j[lt],i);

The fix (2)
Code:
      if(m==0)
      j[0] = &quot;Hello&quot;;
      if(m==1)
      j[1] = &quot;Hi there&quot;;
      if(m==2)
      j[2] = &quot;How r ya&quot;;

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top