Search code examples
cpointersdereference

C pointer initialization and dereferencing, what's wrong here?


This should be super simple, but I'm not sure why the compiler is complaining here.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int *n = 5;

  printf ("n: %d", *n);

  exit(0);
}

Getting the following complaints:

foo.c: In function ‘main’:
foo.c:6: warning: initialization makes pointer from integer without a cast

I just want to print the value that the pointer n references. I'm dereferencing it in the printf() statement and I get a segmentation fault. Compiling this with gcc -o foo foo.c.


Solution

  • You set the pointer to memory address 5, so that it points to whatever at address 5 might be. You probably wanted to make it point to an address where the value 5 is stored. For example:

    int v = 5;    // Store the value 5 in a normal variable
    int *n = &v;  // Make n contain the address of v, so that it points to the 
                  // contents of v