【问题标题】:Erro expects argument of type ‘int’, but argument 3 has type ‘int *’Erro 需要类型为“int”的参数,但参数 3 的类型为“int *”
【发布时间】:2021-06-29 12:11:08
【问题描述】:

我正在尝试编译并将每个值的地址显示到数组中。


int i[10] = {1,2,3,4,5,6,7,8,9,10}, x;
float f[10] = {1,2,3,4,5,6,7,8,9,10};
double d[10] = {1,2,3,4,5,6,7,8,9,10};

/*int *p_i = &i;                                                             
                                                                             
float *p_f = &f;                                                             
                                                                             
double *p_d = &d;*/

int main(void){
  printf("\n\tInteger\tFloat\tDouble");
  printf("\n=======================================");

  /* loop to show the address in each element that have the arrayes */
  for(x = 0; x < 10; x++){
    printf("\nElement %d\t%d\t%d\t%d", x+1, &i[x], &f[x], &d[x]);
    // printf("\nElement %d\t%d\t%d\t%d", x+1, p_i++, p_f++, p_d++);         
  }
  printf("\n=======================================\n");
}

如果语法正确,我不明白为什么。我也搜了一下,发现的代码几乎是一样的。

【问题讨论】:

  • 将指针的%d 更改为%p
  • i[x] 是一个int&amp;i[x] 是指向 int 的指针。如果int 是您要打印的内容,那么这就是您应该传递给printf() 的内容。如果指针是您要打印的,那么正确的指令是%p,而不是%d。类似的情况更适用于变量fd:如果你想打印floatdouble,那么对应的指令应该(都)是%f,你不应该使用&amp;。如果你想打印指针,那么指令应该是%p
  • 别忘了将指针指向void*: printf("\nElement %d\t%d\t%d\t%d", x+1, &amp;i[x], &amp;f[x], &amp;d[x]); -> printf("\nElement %d\t%p\t%p\t%p", x+1, (void*)&amp;i[x], (void*)&amp;f[x], (void*)&amp;d[x]);
  • ButchBet,您要打印int 还是指针?

标签: c pointers compiler-errors printf conversion-specifier


【解决方案1】:

您使用了不正确的转换说明符。

当您提供指针类型的参数时,转换说明符 %d 需要 int 类型的参数。

代替

printf("\nElement %d\t%d\t%d\t%d", x+1, &i[x], &f[x], &d[x]);

printf( "\nElement %d\t%p\t%p\t%p", 
        x+1, ( void * )&i[x], ( void * )&f[x], ( void * )&d[x] );

printf( "\nElement %d\t%p\t%p\t%p", 
        x+1, ( void * )( i + x ), ( void * )(f + x ), ( void * )( d + x ) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多