[英]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
通过复制字符串来防止这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.