4

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?

svick
  • 225,720
  • 49
  • 378
  • 501
Kei Nivky
  • 337
  • 2
  • 5
  • 12

5 Answers5

2

You should be assigning the result of strtok into a separate char* variable. You can't assign it back into str.

StilesCrisis
  • 15,646
  • 4
  • 35
  • 58
2

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...
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
2

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.

Community
  • 1
  • 1
sidyll
  • 54,916
  • 12
  • 100
  • 146
1

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...)

sarnold
  • 99,632
  • 21
  • 173
  • 228
0

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
PersianGulf
  • 2,546
  • 5
  • 41
  • 62