简体   繁体   English

C:strtok结构体中的指针

[英]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. 而且我想在txt字符串上使用strtok。 so, in some function that has gRow *row , i do this: 因此,在某些具有gRow *row函数中,我这样做:

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. Shahar。

请注意,strtok会修改字符串-如果您的txt指针指向只读字符串(例如const字符串文字),那么您将获得异常。

You need to allocate the memory for gRow *row ; 您需要为gRow * row分配内存; Then it will work fine, I hope. 我希望这样就可以了。

strtok modifies the string given to it. strtok修改给它的字符串。 If you don't have the right to modify it, you might get a Segmentation Fault. 如果您无权修改它,则可能会遇到细分错误。 strdup prevents that by copying the string. strdup通过复制字符串来防止这种情况。

strtok modifies its first argument. strtok修改其第一个参数。

In case 1 looks like you were passing a pointer to char constant which could not be modified. 如果1看起来像您正在传递一个指向char常量的指针,则该指针不能被修改。

and in case 2 you were passing a modifiable copy of it returned by strdup . 在第2种情况下,您传递了strdup返回的可修改副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM