0

Can anyone explain why this code not work, pls!! Thanks you so much!

#include <stdio.h>

void changer(char * tp)
{
    int i=0;
    tp[0]='b';
}

int main(void)
{
    char *st="aaab";
    changer(st);
    printf("%s",st);
}
  • 1
    try `char st[]="aaab";` – Jean-François Fabre Oct 19 '16 at 11:53
  • When you declare a pointer variable i.e use that ( * ) symbol, you also have to allocate the space that pointer points to. malloc(). If you don't and then use the pointer you are at undefined behavior territory – k_kaz Oct 19 '16 at 11:55
  • @k_kaz when I understood the comments here right: http://stackoverflow.com/questions/40129319/difference-between-0-and-0 this would be legal – Kami Kaze Oct 19 '16 at 11:59
  • @KamiKaze: Assigning a string literal to a pointer is not a problem, but trying to modify a string literal is. – Aleksi Torhamo Oct 19 '16 at 12:05
  • @AleksiTorhamo True enough, but k_kaz didn't point that out. He was talking about the need to allocate it, which is wrong at this point the declaration process works. The modification is the problem as stated by usr. – Kami Kaze Oct 19 '16 at 12:08

2 Answers2

2

This statement

  tp[0]='b';

results in undefined behaviour because tp points to a string literal. You are not allowed to modify a string literal in C.

Instead you could use an array:

 char st[] = "aaab";

which you'd be able to modify.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.P
  • 117,907
  • 20
  • 175
  • 238
  • thank you mate, i though type a[] & type* is same! – Đạt Nguyễn Thành Oct 19 '16 at 11:56
  • 1
    The difference is that `char *st = "aaab"` puts the *address* of the string literal in the pointer `st`, but `char st[] = "aaab"` actually copies the *contents* of the literal into the array's memory. The second form is equivalent to `char st[5]; st[0] = 'a'; st[1] = 'a'; st[2] = 'a'; st[3] = 'b'; st[4] = '\0';` – trent Oct 19 '16 at 12:16
0
  char *st="aaab";

This statement indicates that st is a pointer variable but "aaab" is string constant.

Instead try

  char st[]="aaab";

This statement indicates that it declares st as array [5] of char and copies the contents of the string literal. Here st is a constant pointer.

Vijay S B
  • 1,251
  • 1
  • 13
  • 24
  • Tell me whats wrong in above answer – Vijay S B Oct 19 '16 at 11:59
  • 1
    "st is a pointer variable but "aaab" is [a] string constant": while technically true, this assignment is perfectly allowed in C and what you said doesn't explain OP's problem. As for "This statement indicates that st is [a] pointer constant", that's just not true; it declares `st` as array [5] of `char` and copies the contents of the string literal. usr's answer is correct. – trent Oct 19 '16 at 12:10
  • @trentcl changes incorporated – Vijay S B Oct 19 '16 at 12:16