Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out the value pointed by pointer (C Programming)

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?

like image 250
Pavan Avatar asked Oct 20 '13 23:10

Pavan


People also ask

How do you access the value pointed to by a pointer in C?

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.

How do you point a pointer to a variable?

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".

What does * p mean in C?

In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions.

What does * represent in pointers?

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.


1 Answers

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;
like image 152
LihO Avatar answered Oct 05 '22 23:10

LihO