格式'%d'需要类型为'int'的参数,但参数3的类型为'int *'

时间:2017-07-09 09:41:04

标签: c

我试图创建一个程序来显示int数组中的元素。但我一直在收到警告。这可能会真的被贬低,但我不知道我犯了什么错误。

以下是代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main() {
     int counter;
     int elements[3] = { 22, 52, 95 };

     for (counter = 1; counter <= 3; counter++) {
         printf("Element %d: %d\n", counter, elements);
     }
     return 0;
}

3 个答案:

答案 0 :(得分:3)

此处的问题是您正在尝试打印int,但elements不是int;

这是一个数组

  • 您想使用[]一次检索一个int
  • C中的数组0 - 已编入索引。因此,这意味着您应该从0元素开始访问它们。

检查以下内容:

for(counter = 0; counter < 3; counter++)
     printf("Element %d: %d\n", counter, elements[counter]);

答案 1 :(得分:2)

我认为你的意思是

for(counter = 0; counter < 3; counter++)
{
    printf("Element %d: %d\n", counter, elements[counter]);
}

编辑: 澄清:循环应该从0开始,因为&#34; C&#34;数组是基于0的,最大大小,如果高达&#34; n-1&#34;其中n是数组大小。接下来%d将需要元素而不是数组本身。要访问数组元素,您需要使用&#34; []&#34;操作

答案 2 :(得分:0)

这是您更正后的代码,其中包含有关每次更改的嵌入式评论

#include <stdio.h>    // printf()
// only include headers those contents are actually used
//#include <stdlib.h>
//#include <ctype.h>
//#include <string.h>
//#include <math.h>
//#include <time.h>

int main( void ) // only two valid signatures for 'main()'
                 // 'int main( void )' and
                 // 'int main( int argc, char *argv[] )'
{
     size_t counter;  // sizeof() returns a 'size_t' not an 'int'
     int elements[] = { 22, 52, 95 }; // compiler can make the count

     // indexes start at 0 and end at number of elements -1
     // don't hard code 'magic' numbers.  In this case let the compiler do the work
     for (counter = 0; counter < sizeof(elements)/sizeof(int); counter++)
     {
         // remember to index the array
         // remember that an array name, by itself,
         // degrades to the first address of the array
         // the 'counter' is now a 'size_t' so the format specifier must match
         printf("Element %lu: %d\n", counter, elements[ counter ]);
     }

     return 0;
}
相关问题