I have the following code:

It gives me a segfault when I modify any element in the character string. Why is that? The first two statements print fine but as soon as I modify the value of any element in the character string it gives me an error! I have tried hard but I can't find an explanation for the segfault. For the statement that is causing the segfault I tried str[3] = 'a'; but that too is giving me the same error.

#include<stdio.h>
#include<stdlib.h>


void stringmodify(char *);
int main()
{char *array = "BLAH BLAH";
stringmodify(array);
return 0;


}


void stringmodify(char *str)
{


printf("%s\n", str);

printf("%c\n", str[3]);

*(str+3)='a';





}

I found the error! I had to instantiate the array in main by doing this char str[] = "BLAH BLAH"but what I don't understand is why doesn't the above method work to modify the character string when instantiated like this: char *str = "BLAH BLAH"?? Why does it give a segfault????

Any string you create like this:
"some words"
is a string literal. The memory that those letters occupy is read only. This is part of the C standard; the rules of C. String literals are read only and you cannot change them.

So when you do this:
char *str = "BLAH BLAH"
you create a pointer, str, that is pointing to a string literal. That's fine. But when you do this:
str[3] = 'a'
you are trying to change that string literal. That is not allowed.

If you do this:
char str[] = "BLAH BLAH"
you are making a copy of the string literal, which you put in an array named str, and you are allowed to do whatever you like with that copy.

While the first construct is still allowed in most C compilers, current C++ compilers will issue a warning about assignment of a string constant to a non-const char*.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.