The following program is showing unexpected result
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* num1;
num1 = malloc(100*sizeof(char));
num1 = "38462879";
printf("%s\n",num1);
num1[0]='5';
printf("%s\n",num1);
return 0;
}
I expect it to print the given string and then print the given string with the first letter replaced by 5 instead of 3 in the next line.
But it is printing the given string in first line and then the program is not going ahead.
Can you please help??
By saying
num1 = "38462879";
you're essentially
num1
point to a string literal. (illegal to attempt to modify the content)Later your attempt to modify a part of that literal will invoke undefined behavior. What you need instead is to use strcpy()
, like
strcpy (num1, "38462879");
That said, couple of general suggestion:
int main()
should at least be int main(void)
.sizeof(char)
is defined to be 1
, it's a redundant multiplier.