char str[10];
gets(str);
str = (char[10]) strtok(str, " "); // type error here
由于strtok()
回报char *
,我得到一个类型的错误而没有铸造。有了它我得到以下几点:
error: cast specifies array type
什么是最好的解决这个代码?
char str[10];
gets(str);
str = (char[10]) strtok(str, " "); // type error here
由于strtok()
回报char *
,我得到一个类型的错误而没有铸造。有了它我得到以下几点:
error: cast specifies array type
什么是最好的解决这个代码?
哦,伙计,小心那gets()
! Related question
您不能分配到阵列(换句话说,用它们作为左值)。
char *p = "string";
char array[10];
array = p; /* invalid */
除此之外,您没有正确使用strtok()
。指针返回指向后续的标记,因此您可能需要创建一个单独的字符指针来存储它。
您应该将strtok的结果分配给一个单独的char *变量。你不能把它分配回str。
首先,您不应该将strtok()
的回归分配回您的str
变量。改为使用单独的变量,例如:
char str[10];
gets(str);
char *token = strtok(str, " ");
//use token as needed...
您不能将任何内容分配给数组。即使这个简单的程序将失败:
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
'字符* PTR =的strtok(STR,”“);' – Cyclonecode