C语言 C中一元'*'的无效类型参数(有'int')错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42875580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:37:45  来源:igfitidea点击:

Invalid type argument of unary '*' (have 'int') Error in C

c

提问by Imdad

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main() {

    int a[] = {5, 15, 34, 54, 14, 2, 52, 72};
    int p = &a[1];
    int q = &a[5]; 

    printf(*(p+3));
    printf(*(q-3));
    printf(*(q-p));
    printf(*p<*q);

    return (EXIT_SUCCESS);
}

Errors: "initialization makes integer from pointer without a cast [-Wint-conversion]" and "invalid type argument of unary '*' (have 'int')". First error is shown twice for the initialisation of variables above. Second error is shown for each print statement.

错误:“初始化从指针生成整数而不进行强制转换 [-Wint-conversion]”和“一元 '*' 的无效类型参数(有 'int')”。对于上述变量的初始化,第一个错误显示了两次。每个打印语句都会显示第二个错误。

I'm not sure what is going wrong, anyone know how I can fix this?

我不确定出了什么问题,有人知道我该如何解决这个问题吗?

回答by VHS

You forgot to make pand qintpointers. Also, you forgot to use the format specifier in the printfstatements. Try the following:

你忘了做pqint指点。此外,您忘记在printf语句中使用格式说明符。请尝试以下操作:

#include <stdio.h>
#include <stdlib.h>

/*
* 
*/
int main() {
  int a[] = {5, 15, 34, 54, 14, 2, 52, 72};
  int *p = &a[1];
  int *q = &a[5];   

  printf("%d\n", *(p+3));
  printf("%d\n", *(q-3));
  printf("%d\n", *q-*p);
  printf("%d\n", *p<*q);
  return (EXIT_SUCCESS);
}

回答by Mark Segal

&a[3](or &a[5]) is a pointer type, i.e. int *.

&a[3](或&a[5]) 是指针类型,即int *.

pis defined as int.

p被定义为int

So you need to define pand qas int *, like this:

所以你需要定义pand qas int *,像这样:

int * p = &a[1];
int * q = &a[5];

回答by Edward Karak

The unary operator &yields the address of its operand. The type is of T *, not T. Therefore you cannot assign a int *to an intwithout a cast. The expression

一元运算符&产生其操作数的地址。类型是T *,不是T。因此,您不能在没有强制int *转换的int情况下将 a 分配给 an 。表达方式

&a[1]

yields the address of a[1].

产生 的地址a[1]

I think you mean to define the variables as pointers to int, not just ints.

我认为您的意思是将变量定义为指向 int 的指针,而不仅仅是 ints。

int *p = &a[1];
int *q = &a[5];