例子:
char str[10];
gets(str);
str = (char[10]) strtok(str, " "); // type error here
由于strtok()
返回一个char *
,如果没有进行类型转换,我会得到一个类型错误。使用它后,我得到了以下结果:
error: cast specifies array type
这段代码该如何修复才能最优?
您不应该将strtok()
的结果直接赋值给str
变量。应该使用另一个变量来存储,例如:
char str[10];
gets(str);
char *token = strtok(str, " ");
//use token as needed...
哎呀,小心使用 gets()
函数!相关问题
你不能给数组赋值(换句话说,不能将它们用作左值)。
char *p = "string";
char array[10];
array = p; /* invalid */
strtok()
。返回的指针指向下一个标记,因此你可能需要创建一个单独的char指针来存储它。你不能给数组分配任何东西。即使是这个简单的程序也会失败:
char *foo(void) { }
int main(int argc, char *argv[])
{
char a[1];
a = foo();
return 0;
}
确实如此:
$ make fail
cc fail.c -o fail
fail.c: In function ‘main’:
fail.c:7:4: error: incompatible types when assigning to type ‘char[1]’ from type ‘char *’
make: *** [fail] Error 1
str
重新定义为char *str
,要么找出其他方法来重写程序,而不是尝试对数组进行赋值。(周围的代码是什么样的?你粘贴的代码其实没有太多意义......)在调用函数之前,您可以获取参数:
char mystr[] = "192.168.0.2";
split_ip(myster[]);
char * split_ip( char ip_address[]){
unsigned short counter = 0;
char *token;
token = strtok (ip_address,".");
while (token != '\0')
{
printf("%s\n",token);
token = strtok ('\0', ".");
}
}// end of function def
char* ptr = strtok(str," ");
- Cyclonecode