雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

C语言编译报:error: invalid type argument of ‘unary *’ (have ‘int’)

2024-07-28 37

问题描述

在编译一个很简单的C语言代码时,遇到C语言指针使用不恰当导致编译报错error: invalid type argument of ‘unary *’ (have ‘int’),代码如下:

#include stdio.h
int main(){
  int b = 10;             //assign the integer 10 to variable b
  int *a;                 //declare a pointer to an integer a
  a=(int *)b;            //Get the memory location of variable b cast it
                          //to an int pointer and assign it to pointer a
  int *c;                 //declare a pointer to an integer c
  c=(int *)a;            //Get the memory location of variable a which is
                          //a pointer to b.  Cast that to an int pointer 
                          //and assign it to pointer c.
  printf(%d,(**c));     //报错位置在这里.  
  return 0;
}    

原因和解决

因为变量“c”是指向一个指针的地址,所以,其类型应当为int**,修改为如下:

int **c;
c = a;

完整的代码如下:

#include stdio.h                                                              
int main(){
    int b=10;
    int *a;
    a=b;
    int **c;
    c=a;
    printf(%d,(**c));   //successfully prints 10
    return 0;
}

修改后的代码再编译就正常了。

总结

C语言的指针一定要注意,指针所指向地址本身是什么类型,如上面的代码,指针实际是指向了另外一个指针的地址,指针的值为另外一个指针的地址,而不知最终变量的地址。

更新于:1个月前
赞一波!

文章评论

全部评论