侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

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

码峰
2022-10-30 / 0 评论 / 8 点赞 / 8,238 阅读 / 352 字 / 正在检测是否收录...
广告 广告

问题描述

在编译一个很简单的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语言的指针一定要注意,指针所指向地址本身是什么类型,如上面的代码,指针实际是指向了另外一个指针的地址,指针的值为另外一个指针的地址,而不知最终变量的地址。

8
广告 广告

评论区