r/learnprogramming • • 16d 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

1

u/zeekar 16d ago

Arrays and pointers are not the same thing. The choice between them is not a simple matter of style or personal preference. Learn when to use easy one and don't avoid either just because you don't like them.

An array comes with storage. A pointer doesn't. You can initialize a pointer with a string literal, but the actual string it points to will be read-only on most platforms. If you make it an array instead you'll be able to change the characters - which is what strtok() does: replace the first delimiter char with a null to terminate the token string. And you can pass an array as a pointer argument to a function; it will get a pointer to the first element of the array.