2011-03-28 127 views
22

我有一个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; 
}  

编译器产生一个错误:

error: invalid type argument of ‘unary *’ (have ‘int’) 

有人能解释这个错误手段?

回答

17

由于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; 
} 
+3

还要注意答案中缺少演员。问题中的强制转义隐藏了将'int **'分配给'int *'的行上的问题。 ('c =(int *)&a;') – Thanatos 2013-09-30 22:54:21

5

我重新格式化了您的代码。

误差是位于此行:

printf("%d", (**c)); 

为了修正它,更改为:

printf("%d", (*c)); 

的*检索来自一个地址的值。 **从地址中检索另一个值的值(在这种情况下是一个地址)。

另外,()是可选的。

#include <stdio.h> 

int main(void) 
{ 
    int b = 10; 
    int *a = NULL; 
    int *c = NULL; 

    a = &b; 
    c = &a; 

    printf("%d", *c); 

    return 0; 
} 

编辑:

线:

c = a; 

这意味着指针 'C' 的值等于:

c = &a; 

必须被替换指针'a'的值。因此,'c'和'a'指向相同的地址('b')。输出是:

10 

编辑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; 
} 

输出:

10 
+0

我不知道解决该问题,打印的结果是“ - 108149370“而不是10. – picstand 2011-03-28 07:35:22

+0

是的,阅读编辑;-)它解决了这个问题。 – 2011-03-28 07:37:20

+0

是的桑德罗,然后打印10,但目标是使用双解引用来打印b的值(即10)。 – picstand 2011-03-28 07:43:55

0

一旦你声明一个变量的类型,你不必将它转换为同一类型。所以你可以写a=&b;。最后,你错误地宣布了c。由于您将其指定为地址a,其中a是指向int的指针,因此您必须将其声明为指向int的指针。

#include <stdio.h> 
int main(void) 
{ 
    int b=10; 
    int *a=&b; 
    int **c=&a; 
    printf("%d", **c); 
    return 0; 
} 
+0

是这样做的。谢啦 – picstand 2011-03-28 07:47:19

10

准系统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. 
} 

ELI5:

You have a big plasma TV cardboard box that contains a small Jewelry box that 
contains a diamond. You asked me to get the cardboard box, open the box and 
get the jewelry box, open the jewelry box, then open the diamond to find what 
is inside the diamond. 
"I don't understand", Says the student, "I can't open the diamond". 

Then the student was enlightened. 
相关问题