C differences in row distribution?

I have functions that take char * as their only argument. Then I do some strtok operations. Sometimes it works, and sometimes it does. It depends on how the row was built. For example, here are two cases.

int main()
{
   char glob[] = "/abc/def/ghi";
   char *glob2 = "/abc/def/ghi";

   func(glob);  //this one works
   func(glob2); //this one doesnt work

   return 0;
}

What is the difference between the two distribution methods and why does strtok explode in the second?

+3
source share
4 answers

strtok() basically modifies the input string.

char *glob2 = "/abc/def/ghi";

In the above case, it glob2points to read-only data, and therefore it fails, whereas with ' char glob[] = "/abc/def/ghi";data is not read-only, it is available in a char array. Therefore, it is subject to modification.

+12
source

char [] str1 = "foo" ( , ). .

const char * str = "foo" foo, .

char * str = "foo" , const ( , , , ).

+7

Strtok , .

/ / . .

+6

; strtok_r().

-1

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


All Articles