#include <stdio.h>
int main(void){
char *p = "Hello";
p = "Bye"; //Why is this valid C code? Why no derefencing operator?
int *z;
int x;
*z = x
z* = 2 //Works
z = 2 //Doesn't Work, Why does it work with characters?
char *str[2] = {"Hello","Good Bye"};
print("%s", str[1]); //Prints Good-Bye. WHY no derefrencing operator?
// Why is this valid C code? If I created an array with pointers
// shouldn't the element print the memory address and not the string?
return 0;
}
My Questions are outlined with the comments. In gerneal I’m having trouble understanding character arrays and pointers. Specifically why I can acess them without the derefrencing operator.
When you type “Bye”, you are actually creating what is called a String Literal. Its a special case, but essentially, when you do
What you are doing is assigning the address of this String literal to
p(the string itself is stored by the compiler in a implementation dependant way (I think) ). Technically address to the first element of a char array, as Richard J. Ross III explains.Since it is a special case, it does not work with other types.
By the way, you should likely get a compiler warning for lines like
char *p = "Hello";. You should be required to define them asconst char *p = "Hello";since modifying them is undefined as the link explains.As to the printing code.
This doesnt need a dereferencing operation, since internally
%srequires a pointer(specificallychar *) to be passed, thus the dereferencing is done byprintf. You can test this by passing a value when printf is expecting a pointer. You should get a runtime crash when it tries to dereference it.