1

I made this program in C and I am getting an error I don't know how to fix. Please help me find the error. This is the code I wrote:

#include <stdio.h>

int main(int argc, char *argv[]){
  int x = 98;
  int *g = x;
  printf("This is x: %d, and this is g: %i.\n", x, *g);
  *g=45;
  printf("This is x: %d, and this is g: %i.\n", x, *g);

  return 0;
}

The compiler gives me the following errors:

ex15t.c: In function ‘main’:
ex15t.c:5:12: warning: initialization makes pointer from integer without a cast [enabled by default]

Thanks ahead for any help.

1
  • Can you update your description to actually suggest what you're really trying to do? Your code does not clarify at all. Commented Jul 2, 2013 at 3:35

2 Answers 2

6

The line: int * g = x; is defining variable g of type int *, and then assigning the value of x to it.

Expanded out, this can be read as:

int *g;
g = x;

and this is obviously not what you want, as x is type int and g is type int *.

Assuming that you want g to point to the variable x, instead do this

int * g = &x;

or instead do this, which may be clearer:

int *g;
g = &x;
Sign up to request clarification or add additional context in comments.

Comments

5

currently you are assinging whatever value (98) is in x to the pointer, and sice an int is not a pointer its warning you. What you really want is to get the address of where x is, ie, point to the location of x. So....

int *g = x;

needs to be

int *g = &x;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.