我有一个C程序:
#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)); //ERROR HAPPENS HERE.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器产生错误:
error: invalid type argument of ‘unary *’ (have ‘int’)
Run Code Online (Sandbox Code Playgroud)
有人可以解释这个错误的含义吗?
cod*_*ict 21
由于c
是保存整数指针的地址,因此其类型应为int**
:
int **c;
c = &a;
Run Code Online (Sandbox Code Playgroud)
整个计划变为:
#include <stdio.h>
int main(){
int b=10;
int *a;
a=&b;
int **c;
c=&a;
printf("%d",(**c)); //successfully prints 10
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ski 14
Barebones C程序产生上述错误:
#include <iostream>
using namespace std;
int main(){
char *p;
*p = 'c';
cout << *p[0];
//error: invalid type argument of `unary *'
//peeking too deeply into p, that's a paddlin.
cout << **p;
//error: invalid type argument of `unary *'
//peeking too deeply into p, you better believe that's a paddlin.
}
Run Code Online (Sandbox Code Playgroud)
ELI5:
大师将一块闪亮的圆形石头放在一个小盒子里,然后送给学生.大师说:"打开盒子,取下石头".学生这样做了.
然后主人说:"现在打开石头,取下石头".学生说:"我不能开石头".
然后学生开悟了.
我重新格式化了你的代码.
错误位于此行:
printf("%d", (**c));
Run Code Online (Sandbox Code Playgroud)
要修复它,请更改为:
printf("%d", (*c));
Run Code Online (Sandbox Code Playgroud)
*从地址中检索值.**从地址中检索另一个值的值(在这种情况下为地址).
另外,()是可选的.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
这条线:
c = &a;
Run Code Online (Sandbox Code Playgroud)
必须替换为:
c = a;
Run Code Online (Sandbox Code Playgroud)
这意味着指针'c'的值等于指针'a'的值.因此,'c'和'a'指向相同的地址('b').输出是:
10
Run Code Online (Sandbox Code Playgroud)
编辑2:
如果你想使用双*:
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
10
Run Code Online (Sandbox Code Playgroud)