I'm working on some C code. In one of .c files I can see something like:
char* test = ("someChar", "someChar2", 3);
When I print out this variable, I get "3" on my screen.
What is happening in this part of code? Why do I get 3 as a result of printing out this char*? I am the most curious about this ("someChar", "someChar2", 3)
expression.
EDIT(after the issue has been resolved):
What made me scratch my head was also the fact, that there are two chars and one int in this expression.
If we use printf("%u", test)
we can get this number, but this code definitely doesn't look clean and I believe this is not an elegant way of assigning number to char*.
Its because of comma
operator & manual page of operator
says when in an expression if multiple comma are there then solve from Left to Right
but it considers right most argument.
In the statement
char* test = ("someChar", "someChar2", 3);
test
get assigned with right most argument that is 3
. And now it looks like
char *test = 3;
since test
is char pointer
& it should initialize with valid address and 3
is not the valid address. So if you are just printing test
like
printf("%d\n",test);
that doesn't cause any error but that causes undefined behavior. And if you are going to dereference it like *test
then your program get crashed(Seg. fault), this is one of possible scenario you should keep in mind while dealing with pointers.