Reputation: 377
Example:
char str[10];
gets(str);
str = (char[10]) strtok(str, " "); // type error here
Since strtok()
returns a char *
, I get an type error without that casting. With it I get the following:
error: cast specifies array type
What is the best to fix this code?
Upvotes: 4
Views: 3200
Reputation: 2935
You can get parameter before calling your function:
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
Upvotes: 0
Reputation: 59287
Oh man, be careful with that gets()
! Related question
You can't assign to arrays (in other words, use them as lvalues).
char *p = "string";
char array[10];
array = p; /* invalid */
Apart from that, you're not using strtok()
correctly. The pointer returned points to the subsequent token, so you might want to create a separate char pointer to store it.
Upvotes: 2
Reputation: 104050
You cannot assign anything to an array. Even this simplistic program will fail:
char *foo(void) { }
int main(int argc, char *argv[])
{
char a[1];
a = foo();
return 0;
}
As indeed it does:
$ 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
Either re-define str
as char *str
or figure out some other way to re-write your program to not attempt to assign to an array. (What does the surrounding code look like? The code you've pasted doesn't really make sense anyway...)
Upvotes: 1
Reputation: 595762
You should not be assigning the reult of strtok()
back to your str
variable in the first place. Use a separate variable instead, eg:
char str[10];
gets(str);
char *token = strtok(str, " ");
//use token as needed...
Upvotes: 2
Reputation: 16290
You should be assigning the result of strtok into a separate char* variable. You can't assign it back into str.
Upvotes: 2