-
char pointer problem
Hello
Why will this lead to crash:
Code:
char *tmp = "(some)(stupid)(string)\0";
char *p = tmp;
int length = strlen(tmp);
if ( (p[0] == '(') && (p[length-1] == ')') ) {
p[length-1] = '\0';
p++;
length--;
printf("%s \n", p);
}
I just want to remove parenthesis at the begging and end..
Thanks for help
-
Code:
char *tmp = "(some)(stupid)(string)\0";
The compiler places that string on non-modifyable memory space, but it is legal to have a pointer to it. It is a constant string. If you need to modify it, acquire a copy first.
-
If you want a copy, then make an array:
Code:
char tmp[] = "(some)(stupid)(string)\0";
That will make tmp an array that starts out with an implicit copy of the string from its read-only location.
Also, string literals don't need to have the '\0' char appended at the end. If the array is big enough to hold the array, the '\0' will be there in the array. By not specifying the size, the array is made large enough to hold the entire array + the '\0'. So this is all you really need:
Code:
char tmp[] = "(some)(stupid)(string)";