我想知道,是否有另一种解决方案可以修改为字符串文字,该解决方案是否真的有效且最佳?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strdup(const char *src) {
char *dst = malloc(strlen (src) + 1);
Space for length plus nul
if (dst == NULL) return NULL;
No memory
strcpy(dst, src); // Copy the characters
return dst; // Return the new string
}
int main( void )
{
const char* s1= " hello "; // A constant character pointer pointing to the string " serhat".
char* s2= strdup(s1);
s2[1]= 'b';
printf("%s", s2);
}
代码不会修改字符串文字,它只是修改分配的副本。您可以使用更简单的方法,使用初始化数组
char
:
#include <stdio.h>
int main() {
char s1[] = " hello ";
s1[1]= 'b';
printf("%s\n", s1);
return 0;
}