C 程序永远不会从 strtok() 函数返回的问题
我正在做一项大学作业,并且一直在绞尽脑汁地解决一个奇怪的问题:我的程序调用 strtok
并且永远不会返回。
我的代码如下所示:
int loadMenuDataIn(GJCType* menu, char *data)
{
char *lineTokenPtr;
int i;
lineTokenPtr = strtok(data, "\n");
while (lineTokenPtr != NULL) {
/* ... */
}
}
我在网上查找了很多网站,但我看不出我使用 strtok
的方式有什么问题,而且我无法确定为什么我的代码会出现这种情况停留在行 lineTokenPtr = strtok(data, "\n");
任何人都可以帮我解释一下吗?
(如果有什么区别,请使用 OSX 和 Xcode)
I am working on a university assignment and I've been wracking my head around a weird problem where my program calls strtok
and never returns.
My code looks like:
int loadMenuDataIn(GJCType* menu, char *data)
{
char *lineTokenPtr;
int i;
lineTokenPtr = strtok(data, "\n");
while (lineTokenPtr != NULL) {
/* ... */
}
}
I've looked up a bunch of sites on the web, but I cant see anything wrong with the way that I am using strtok
and I cant determine why it would my code would get stuck on the line lineTokenPtr = strtok(data, "\n");
Can anyone help me shed some light on this?
(Using OSX and Xcode if it makes any difference)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你检查过论证的内容了吗?它是 \0 终止的吗?
您通过的参数是可写内存吗? strtok 在标记字符串时将其作为第一个参数写入缓冲区。
如果你写的话
have you checked the contents of the argument? is it \0 terminated?
the argument that you pass, is it writeable memory? strtok writes to the buffer that it gets as first argument when it tokenizes the string.
IOW if you write
函数
strtok()
将字符串中实际的标记定界符号替换为空字符(即\0
),并返回指向标记开头的指针字符串。因此,在使用换行符分隔符号重复调用strtok()
后,看起来像在内存中的字符串缓冲区将被原地修改并转换
为返回
char
指针来自指向字符串the Fox\0
、ran over\0
和the hill\0
的strtok()
代码>.没有分配新的内存...原始字符串内存被就地修改,这意味着不要传递 const char* 类型的字符串文字很重要。The function
strtok()
replaces the actual token delimiting symbols in the character string with null (i.e.,\0
) chars, and returns a pointer to the start of the token in the string. So after repeated calls tostrtok()
with a newline delimiting symbol, a string buffer that looked likein memory will be literally modified in-place and turned into
with
char
pointers returned fromstrtok()
that point to the stringsthe fox\0
,ran over\0
, andthe hill\0
. No new memory is allocated ... the original string memory is modified in-place, which means it's important not to pass a string literal that is of typeconst char*
.