I would like to print out the contents a pointer pointing to. Here is my code:
int main(){
int* pt = NULL;
*pt = 100;
printf("%d\n",*pt);
return 0;
}
This gives me a segmentation fault. Why?
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
Pointers are said to "point to" the variable whose address they store. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator ( * ). The operator itself can be read as "value pointed to by".
In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions.
In an expression, *pointer refers to some object using its memory address. A declaration such as int *pointer means that *pointer will refer to an int . Since *pointer refers to an int , this means that pointer is a pointer to an int . This is explained further here and here.
These lines:
int* pt = NULL;
*pt = 100;
are dereferencing a NULL
pointer (i.e. you try to store value 100
into the memory at address NULL
), which results in undefined behavor. Try:
int i = 0;
int *p = &i;
*p = 100;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With