剥去C中字符串的结尾

ali*_*_fn -2 c string parsing pointer-arithmetic

我需要一个函数来)从字符串的末尾删除字符.例如,hello,world)应该转换为hello,world.

我写了这个:

char *a="hello,world)";
int a_len=strlen(a);
*(a+a_len-1)='\0';
printf("%s", a);
Run Code Online (Sandbox Code Playgroud)

但输出中没有显示任何内容.

Ser*_* L. 6

理想情况下,您应该获得分段违例运行时错误.

您已经指定了一个指向驻留在只读内存中的字符串文字的指针.试图修改那个很糟糕!

尝试将其复制到堆栈中

char a[] ="hello,world)";
Run Code Online (Sandbox Code Playgroud)

如果你真的必须使用动态内存(请在你的问题中写下),那么你必须在那里手动复制你的字符串:

char *a = malloc(sizeof("hello,world)"));
memcpy(a, "hello,world)", sizeof("hello,world)"));
int a_len=strlen(a);
a[a_len - 1] = '\0';
Run Code Online (Sandbox Code Playgroud)

或者你也可以让printf截断你的字符串:

printf("%.*s", strlen(a) - 1, a);
Run Code Online (Sandbox Code Playgroud)

也正如Basile指出的那样 strdup

char * a = strndup("hello,world)", sizeof("hello,world)") -2);
Run Code Online (Sandbox Code Playgroud)

请注意,这里我们必须截断两个字符,因为sizeof包含null终止符,但strndup总是会添加一个.


归档时间:

查看次数:

148 次

最近记录:

11 年,7 月 前