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);
}
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);
}
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.
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.