1

我用 C 语言编写了这个程序,但出现了一个我不知道如何修复的错误。请帮我找出错误。这是我写的代码:

#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;
}

编译器给我以下错误:

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

提前感谢您的帮助。

4

2 回答 2

6

行:int * g = x;定义g类型的变量int *,然后为其赋值x

展开,可以读作:

int *g;
g = x;

这显然不是你想要的,就像xtypeintgtype一样int *

假设您要g指向变量x,而是这样做

int * g = &x;

或者改为这样做,这可能更清楚:

int *g;
g = &x;
于 2013-07-02T03:44:39.270 回答
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;
于 2013-07-02T03:35:03.370 回答