When we declare a
string and initialize it with a string literal like
string s = "kray";
string is stored in a read-only memory location. And that's why you get a segmentation fault when you then try to access the characters of this
string and change their values.
apparently, I misunderstood your question. I didn't notice that you were talking about an empty
I assume that's what you mean by an empty string
string variable, unlike other types of variables (e.g.,
int), is little bit different in a way that's it's actually an array of characters underneath the hood.
You'll know more about that later on in the course, but for you not to be confused, you should be informed that we need to know the size of the
string beforehand in order to reserve a big enough block of memory to store it on unless you're initializing it with a string literal (or an initializer list in case of a
When you declare a
s the way we did up here then you try to access a
char in that it like
s, you get a segmentation fault because we didn't really ask our computer yet to reserve a block of memory to store that
string on, so our computer assumes that no memory reserved for that and you're trying to access something that should really be accessed yet.
A simple way to create an empty editable
string is to use a
char array. For example,
char str[size+1]; // empty string
size is the number of characters in that
string and the
+1 is for the null terminator (i.e.,