TIL: replacing characters in an array
published
last modified
3kb
I was getting an error if I tried to initialise an array as so, and change values in it.
The Right Way but Why?
Oh, String Literals
I found my answer. The key is to understand string literals in c.
Specifically, is that they are not modifiable and in fact are usually placed into read-only memory. Thus doing something like:
Would fail, because this is a string literal.
And especially on line 9 when:
This is a memory access error, im not allowed to touch it. This will be undefined behaviour causing my program to crash.
What to Do Instead
We have to initiliase an array of chars:
This way the string literal is copied into an array of characters (into modifiable memory) and I can change the characters in it.
Hope whoever comes across this now understands it a bit better. Thanks folks!
Contact
If you have any comments or thoughts you can reach me at any of the places below.