How would I get my replace_char function to work properly?
The way that I am trying it in the function below returns segmentation faults using gcc in Ubuntu.
I have tried other ways, but each time I try to change the value, I get a fault.
int main (void)
{
char* string = "Hello World!";
printf ("%s\n", string);
replace_char(str开发者_StackOverflow中文版ing, 10, 'a');
printf ("%s\n", string);
}
void replace_char(char str[], int n, char c)
{
str[n] = c;
}
There is nothing wrong with your replace_char
function. The problem is that you are trying to modify a string literal ("Hello World!") and that's undefined behavior. Try making a copy of the string instead, like this:
char string[] = "Hello World!";
Edit
To get the 'suggestion' of editing string
in place, you can edit the pointer inplace:
void replace_char(char*& str, int n, char c)
{
str = strdup(str);
str[n] = c;
}
int main()
{
char* string = "Hello World!";
string = replace_char(string, 10, 'a');
// ...
free(string);
}
Note you now have to remember to call free
on the string after calling this. I suggest, instead, that you do what I suggested before: wrap the literal in strdup if required. That way you don
't incur the cost of allocating a copy all the time (just when necessary).
The problem is that "Hello World' is a const literal char array.
const char* conststr = "Hello World!";
char * string = strdup(conststr);
i assume the problem will be gone
Explanation: Compilers can allocate string literals in (readonly) data segment. The conversion to a char* (as opposed to const char*) is actually not valid. If you use use e.g.
gcc -Wall test.c
you'd get a warning.
Fun experiment:
Observe here that (because it is Undefined Behaviour) compilers can do funny stuff in such cases:
http://ideone.com/C39R6 shows that the program wouldn't 'crash' but silently fail to modify the string literal unless the string was copied.
YMMV. Use -Wall, use some kind of lint if you can, and do unit testing :){
精彩评论