Cast char * to char []

Example:

char str[10]; gets(str); str = (char[10]) strtok(str, " "); // type error here 

Since strtok() returns a char * , I get a type error without this casting. With it, I get the following:

 error: cast specifies array type 

What is the best way to fix this code?

+4
source share
5 answers

Oh my god, be careful with this gets() ! Question related to us


You cannot assign arrays (in other words, use them as lvalues).

 char *p = "string"; char array[10]; array = p; /* invalid */ 

Also, you are not using strtok() correctly. The pointer returns points to the next token, so you might want to create a separate char pointer to save it.

+2
source

You must assign the result of strtok to a separate char * variable. You cannot assign it back to the page.

+2
source

You should not assign the result of strtok() back to your str variable in the first place. Instead, use a separate variable, for example:

 char str[10]; gets(str); char *token = strtok(str, " "); //use token as needed... 
+2
source

You cannot assign an array to an array. Even this simplified program will not work:

 char *foo(void) { } int main(int argc, char *argv[]) { char a[1]; a = foo(); return 0; } 

As this happens:

 $ 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 

Redefine str as char *str or define another way to rewrite your program so as not to try to assign an array. (What does the surrounding code look like? The code you inserted does not really make sense ...)

+1
source

You can get the parameter before calling the 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 
0
source

Source: https://habr.com/ru/post/1385257/


All Articles