问题
I'm trying to terminate a character pointer in c, at a specific location by setting the null terminator to it.
for examples if I have a char pointer
char *hi="hello";
I want it to be "hell" by setting the o to null.
I have tried doing this with strcpy with something like
strcpy(hi+4, "\0");
But it is not working.
回答1:
"hello" is a string literal so it cannot modified, and in your code, hi points to the first element in such a literal. Any attempt to modify the thing it points to is undefined behaviour.
However, if you create your own char array, you can insert a null terminator at will. For example,
char hi[] = "hello"; // hi is array with {'h', 'e', 'l', 'l', 'o', '\0'}
hi[4] = '\0';
Here, hi is a length 6 array of char which you own and whose contents you can modify. After setting the 5th element, it contains {'h', 'e', 'l', 'l', '\0', '\0'}, and printing it would yield hell.
回答2:
Point 1:
In your code
char *hi="hello";
hi is a pointer to a string literal. It may not be modifiable. You've to use a char array instead and initialize that with the same string literal. Then you can modify the contenets of that array as you may want.
Point 2:
You don't need strcpy() to copy a single char. You can simply assign the value using the assignment operator =.
Note: You don't terminate a pointer, you terminate achar array with a null-terminator to make that a string.
回答3:
If the string is a literal you can't modify it. Otherwise:
To terminate a C string after 4 characters you could use:
*(he+4) = 0;
or
he[4] = 0;
he[4] = '\0';
or, since strcpy() copies all the characters specified and then appends a '\0' character:
strcpy(he+4, "");
but this is rather obfuscated.
来源:https://stackoverflow.com/questions/29666162/how-to-terminate-a-character-pointer-at-a-certain-location-in-c