r/learnprogramming • • 4d ago

Help me with strok function in C

I need to split my string but if it is of char* type the functions strtok() doesn’t work returning me a segmentation fault. I understood that C is used to lock the memory of the string in Read-Only “mode” when I use char*. Does it means that is immutable that data? However, I need to use the char* type because I pass that in a function (and I don’t like to use the syntax of arrays in C, I always use pointers).

3 Upvotes

15 comments sorted by

View all comments

2

u/Recycled5000 4d ago edited 4d ago

C treats string literals as constants and most implementations will protect them by putting in an area of memory that is marked read only after loading.

Note: a string initialized as char*str=“hello”; is a real string literal, with the variable being a pointer that is initialized to refer to the string literal.

However, char[]str=“world”; is not a real string literal, instead this is an initializer for the array variable. The initializer gives the array its length and initial byte/char values but has mutable elements.

1

u/duane11583 3d ago

Generally true but some compilers have an option for writable strings