我有以下代码:
char buffer[50];
char * tok, tok2;
buffer = "addition 1 2";
tok = strtok(buffer, " ");
// get the second token
tok = strtok(NULL, " ");
tok2 = tok;
// get the last token
tok = strtok(NULL, " ");
// pass them to the function
foo(atoi(tok2), atoi(tok));
但是,我遇到了段错误 11。我想做的是存储第二个值(整数 1)和最后一个值(整数 2)并将它们传递给 foo(int a, int b)。我怎么能这样做?
最佳答案
char * tok, tok2;
上述语句将tok
定义为char *
类型,将tok2
定义为char
类型。相当于
char *tok;
char tok2;
char *
不是新类型。您应该始终将 *
与变量相关联,而不是类型。
您应该将该语句更改为
char *tok, *tok2;
您不能在 C
中分配数组。因此下面的说法是错误的——
buffer = "addition 1 2";
你应该做的是用字符串文字初始化数组buffer
-
char buffer[] = "addition 1 2";
另外,请注意函数 strtok
修改了它的第一个参数。它的签名是
char *strtok(char *str, const char *delim);
正是由于这个原因,第一个参数 str
不像第二个参数 delim
那样不是 const
限定的。
关于c - 使用 strtok 中的值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566424/