Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* and char[] are not same type? [duplicate]

Tags:

c

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I'm experiencing a strange issue with my C code. I'm trying to split string using strtok function, but I get access violation exception. Here's 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 don't get any error.

Anyone can explain why I get that (strange for me) behavior with strtok? I thought char* and char[] was the same and exact type.

UPDATE

I'm using MSVC 2012 compiler.

like image 479
Davita Avatar asked Dec 03 '22 01:12

Davita


1 Answers

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

char* line = "...";

then a string literal is being modified, which is undefined behaviour. When you use:

char[] line = "...";

then a copy of the string literal is being modified.

like image 110
hmjd Avatar answered Dec 27 '22 03:12

hmjd