Srikar Srikar - 3 months ago 11
C Question

The below code snippets produce the same output. But which is right?

The below code snippet is the wrong one.......but seems to work correctly

#include <stdio.h>

void fun(char* msg);

int main()
{
char* str = "Hello";
printf("%s\n",str);

fun(&str);

printf("%s\n",str);
return 0;

}

void fun(char* msg){
*msg = "World";

}


And now the correct code snippet

#include <stdio.h>

void fun(char** msg);

int main()
{
char* str = "Hello";
printf("%s\n",str);

fun(&str);

printf("%s\n",str);
return 0;

}

void fun(char** msg){
*msg = "World";

}


The objective of the above code is to modify the value of str.
Both codes produce the same output but why does the wrong code seems to work correctly in this case.

Answer

The first one should not compile, because &str is a char**, but the function is declared to take a char*.

Additionally, in *msg = "World";, "World" is a char* but *msg is a single char.

Comments