[英]Access violation In C Trying to Use strtok in a function
I am trying to pass a string to a function and tokenize the string, but it gives me an access violation error when it tries to execute strtok.我正在尝试将一个字符串传递给 function 并对该字符串进行标记化,但它在尝试执行 strtok 时给我一个访问冲突错误。
int main(void) {
char String1[100];
// note: I read data into the string from a text file, but I'm not showing the code for it here
tokenize(String1);
return 0;
}
void tokenize(char data[]) {
strtok(data, ','); // gives me an access violation error
}
When I used strtok in main, it works, but not when I pass it to the function.当我在 main 中使用 strtok 时,它起作用了,但当我将它传递给 function 时却不起作用。
You should consult man strtok for more detail.您应该咨询man strtok以获取更多详细信息。 And it's advisable to use strtok_r
instead of strtok
.并且建议使用strtok_r
而不是strtok
。
#include <stdio.h>
#include <string.h>
void tokenize(char data[]) {
char *token = data;
while (1) {
token = strtok(token, ",");
if (!token) {
break;
}
printf("token : %s\n", token);
token = NULL;
}
}
int main(void) {
char String1[] = "a,b,c,d,e,f,g";
// note: I read data into the string from a text file, but I'm not showing the
// code for it here
tokenize(String1);
return 0;
}
If your compiler is not giving you plenty of warnings about this code, please enable more warnings .如果你的编译器没有给你很多关于这段代码的警告,请启用更多警告。
#include <string.h>
to get the prototype for strtok()
.您需要#include <string.h>
来获取strtok()
的原型。tokenize()
, or more simply, just move its definition above main()
.您要么需要tokenize()
的原型,要么更简单地说,只需将其定义移到main()
之上。strtok()
should be a char *
, not a char
. (您的实际错误所在) strtok()
的第二个参数应该是char *
,而不是char
。 So change ','
to ","
.因此,将','
更改为","
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.