Pavan
Pavan

Reputation: 2851

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?

Upvotes: 5

Views: 50742

Answers (2)

LihO
LihO

Reputation: 42083

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;

Upvotes: 12

John3136
John3136

Reputation: 29265

Because you are trying to write to address NULL.

Try:

int main(){
    int val = 0;
    int* pt = &val;
    *pt = 100;
    printf("%d\n",*pt);
    return 0;
}

Upvotes: 5

Related Questions