Char * and char [] are not the same?

Possible duplicate:
Why does a segmentation error occur when writing to a string?

I am having a strange problem with my C code. I am trying to split a string using the strtok function, but I am getting an access violation exception. Here is my code:

char *token; char *line = "LINE TO BE SEPARATED"; char *search = " "; token = strtok(line, search); <-- this code causes crash 

However, if I change char *line to char line[] , everything works as expected, and I get no errors.

Can anyone explain why I get this (strange to me) behavior with strtok? I thought char * and char [] are the same and exact type.

UPDATE

I am using the MSVC 2012 compiler.

+4
source share
4 answers

When assigning "LINE TO BE SEPARATED" to char *line you make a line point to a constant string recorded in the executable software. You are not allowed to change it. You must declare a variable like const char * .

When declared as char[] , your string is declared on the stack of your function. That way you can change it.

+5
source

strtok() modifies the string that it parses. If you use:

 char* line = "..."; 

then the string literal is changed, which is undefined. When you use:

 char[] line = "..."; 

then the string literal is copied.

+8
source
 char *s = "any string" 

is the definition of a pointer pointing to a string or char (s) array. in the above example, s points to a constant string

 char s[] = "any string" 

is the definition of the char (s) array. in the above example, s is an array of char (s) that contains charcters {'a','n','y',' ','s','t','r,'i','n','g','\0'}

strtock modifies the contents of the input string. it replaces the delimiters in your string with '\0' (null).

So you cannot use strtok with constant lines like this:

 char *s="any string" 

you can use strtok with dynamic memory or static memory:

 char *s = malloc(20 * sizeof(char)); //dynamic allocation for string strcpy(s,"any string"); char s[20] = "any string"; //static allocation for string char s[] = "any string"; //static allocation for string 
+3
source

To answer your question: char* and char[] are not same type?

It:

 char *line = "LINE TO BE SEPARATED"; 

It is a string literal defined in read-only memory. You cannot change this line.

This, however:

 char line[] = "LINE TO BE SEPARATED"; 

Now this is an array of characters (the quoted text was copied to the array) pushed onto the stack. You are allowed to change the characters in this array.

Thus, they are character arrays, but are placed in different parts of the memory.

+1
source

All Articles