Y
yaru22
Hi, I'm relatively new to C programming and was quite confused by this
error.
What I tried to do is that if I have a string with double quotes
around it (i.e. char *str = "\"hello\""
, I have to remove the
quotes.
So I programmed this as follow:
#include <stdio.h>
#include <string.h>
int change(char *str) {
int len = strlen(str);
if (str[0]=='\"' && str[len-1]=='\"') {
char str_tmp[len+1];
strncpy(str_tmp,str+1,len-2);
str_tmp[len-2]='\0';
*str = *str_tmp;
}
return 0;
}
int main() {
char *str = "\"hello\"";
change(str);
printf("%s\n",str);
return 0;
}
However, if I run this code, I get segmentation fault error.
I guess "*str = *str_tmp;" part is wrong, but I don't know how to fix
it.
Doesn't this statement mean, substitute the value of str_tmp into the
memory location that str is pointing to?
I wonder what the reason for the error and how to do it.
Also, the return type of the function "change" should be int.
Thanks in advance.
Brian
error.
What I tried to do is that if I have a string with double quotes
around it (i.e. char *str = "\"hello\""
quotes.
So I programmed this as follow:
#include <stdio.h>
#include <string.h>
int change(char *str) {
int len = strlen(str);
if (str[0]=='\"' && str[len-1]=='\"') {
char str_tmp[len+1];
strncpy(str_tmp,str+1,len-2);
str_tmp[len-2]='\0';
*str = *str_tmp;
}
return 0;
}
int main() {
char *str = "\"hello\"";
change(str);
printf("%s\n",str);
return 0;
}
However, if I run this code, I get segmentation fault error.
I guess "*str = *str_tmp;" part is wrong, but I don't know how to fix
it.
Doesn't this statement mean, substitute the value of str_tmp into the
memory location that str is pointing to?
I wonder what the reason for the error and how to do it.
Also, the return type of the function "change" should be int.
Thanks in advance.
Brian