0

code:

char *m[10];
char * s;

int lcounter=0;
int sd=0;
char mem_buf [ 500 ];
while ( fgets ( mem_buf, sizeof mem_buf, infile ) != NULL )
{

    m[lcounter] =(char *) malloc(10*sizeof(char));

    item = strtok(mem_buf,delims);
    m[lcounter]=item;
    printf("\n value inside==== :%s:",m[lcounter]);
    lcounter=lcounter+1;

}

for(i=0;i<lcounter;i++)
{
    printf("\n value outside==== :%s:",m[sd]);
    sd++;
}

input:

goo|
bbb|
ccc|

When I execute this am getting below output:

value inside==== : goo
value inside==== : bbb
value inside==== : ccc

value outside====:ccc
value outside====:ccc
value outside====:ccc

But I need like:

value outside====:goo
value outside====:bbb
value outside====:ccc
2
  • @stefan Your comment doesn't make any sense. The culprit is m[lcounter]=item. Commented Feb 26, 2011 at 7:50
  • @chrisaycock: You are right :) I will remove it, i missed the strtok ;) Commented Feb 26, 2011 at 7:52

2 Answers 2

1

Use strcpy if you want it to last outside of the loop. strtok may reuse the same pointer.

Sign up to request clarification or add additional context in comments.

1 Comment

ya i did small change that u suggest, i got it. thanks a lot.
1

This won't copy a C string:

m[lcounter]=item;

Instead, use:

strcpy(m[lcounter], item);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.