-2

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.

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
alireza_fn
  • 884
  • 1
  • 8
  • 21

3 Answers3

6

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.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
1

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

barak manos
  • 29,648
  • 10
  • 62
  • 114
-2

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);
alireza_fn
  • 884
  • 1
  • 8
  • 21