开发者

C: strtok on pointer inside a struct

I have struct with this definition:

typedef struct gRow{
    char *txt;
    char *fileName;
    int line;
} gRow;

and i want to use strtok on the txt string. so, in some 开发者_如何学Cfunction that has gRow *row, i do this:

strtok(row->txt, SEPERATOR_CHARACTERS);

and this is the point where i get Segmentation Fault. if i replace it with:

strtok(strdup(row->txt), SEPERATOR_CHARACTERS);

it works just fine. any ideas why?

Thanks.

Shahar.


Note that strtok modifies the string - if your txt pointer is pointing at a read-only string (e.g. a const string literal) then you will get an exception.


You need to allocate the memory for gRow *row ; Then it will work fine, I hope.


strtok modifies the string given to it. If you don't have the right to modify it, you might get a Segmentation Fault. strdup prevents that by copying the string.


strtok modifies its first argument.

In case 1 looks like you were passing a pointer to char constant which could not be modified.

and in case 2 you were passing a modifiable copy of it returned by strdup.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜