开发者

problem using pointer array?

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
val开发者_运维技巧ue outside====:bbb
value outside====:ccc


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


This won't copy a C string:

m[lcounter]=item;

Instead, use:

strcpy(m[lcounter], item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜