As far as I know, a string literal can't be modified for example:
char* a = "abc";
a[0] = 'c';
That would not work since string literal is read-only. I can only modify it if:
char a[] = "abc";
a[0] = 'c';
However, in this post, Parse $PATH variable and save the directory names into an array of strings, the first answer modified a string literal at these two places:
path_var[j]='\0';
array[current_colon] = path_var+j+1;
I'm not very familiar with C so any explanation would be appreciated.
Code blocks from the post you linked:
First block:
getenv()returns a pointer to a string which is pointed to byorig_path_var. The string thatget_env()returns should be treated as a read-only string as the behaviour is undefined if the program attempts to modify it.strdup()is called to make a duplicate of this string. The waystrdup()does this is by callingmalloc()and allocating memory for the size of the string + 1 and then copying the string into the memory.malloc()is used, the string is stored on the heap, this allows us to edit the string and modify it.Second block:
arraypoints to a an array ofchar *pointers. There isnb_colons+1pointers in the array.arrayis initilized topath_var(remember it is not a string literal, but a copy of one).current_colonth element ofarrayis set topath_var+j+1. If you don't understand pointer arithmetic, this just means it assigns the address of thej+1th char ofpath_vartoarray[current_colon].As you can see, the code is not operating on
conststring literals likeorig_path_var. Instead it uses a copy made withstrdup(). This seems to be where your confusion stems from so take a look at this:The above text shows what
strdup()does according to its man page.It may also help to read the
malloc()man page.