I need a function to remove ) character from end of a string. for example, hello,world) should be converted to hello,world.

I have written this :

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

but nothing is shown in the output.

有帮助吗?

解决方案

You should ideally be getting a segmentation violation runtime error.

You have assigned a pointer to a string literal which resides in read-only memory. Trying to modify that is bad!

Try copying it onto the stack

char a[] ="hello,world)";

If you really have to use dynamic memory (please write that in your question) then you have to manually copy your string there:

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

Alternatively you can also have printf truncate your string:

printf("%.*s", strlen(a) - 1, a);

Also as Basile pointed out there is strdup

char * a = strndup("hello,world)", sizeof("hello,world)") -2);

Note that here we have to truncate by two characters because sizeof includes the null terminator, but strndup will always add one.

其他提示

Analysis:

Line #1: char *a="hello,world)";

Variable a points to an array of characters, located in the (read-only) code section of the program

Line #3: *(a+a_len-1)='\0';

A memory access violation occurs, when the CPU attempts to write into a read-only memory section

Solution:

Line #1: char a[]="hello,world)";

Variable a is an array of characters located in the stack of the program, which is a read/write section

I must use dynamic memory so I have to leave char[].

trying this also does not work:

char *a=malloc(4);
a="hello,world)";
int a_len=strlen(a);
*(a+a_len-2)='\0';
printf("%s", a);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top