Printing out the value pointed by pointer (C Programming)

49,307

Solution 1

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;

Solution 2

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;
}
Share:
49,307
Pavan
Author by

Pavan

Updated on October 21, 2020

Comments

  • Pavan
    Pavan over 3 years

    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?

    • Ed Heal
      Ed Heal over 10 years
      When you point to something it has to exist. Try malloc and then it will exist!