【问题标题】:Why is the argument type incorrect (it is int when it should be int *)?为什么参数类型不正确(应该是 int * 时是 int)?
【发布时间】:2019-04-24 12:26:27
【问题描述】:

我正在用 C 编写一个程序,它扫描值并按照“团队 1 值 1、团队 2 值 1、团队 1 值 2、团队 2 值 2”等顺序打印出值。 我在'printf("Team 1 weights: %i\n", team1);'这一行不断收到错误消息带有消息“格式指定 int 类型,但参数的类型为“int *”,我不知道为什么。我认为这可能与数组有关。 如有任何帮助,我将不胜感激!

#include <stdio.h>
#include <math.h>

int main() {

    printf("How many members of each team are there?\n");

    int team1 [] = {110, 113, 112, 117};
    int team2 [] = {106, 102, 121, 111};

    scanf("%i", &team1[4]);
    printf("How much do the players of team 1 weigh?\n");
    scanf("%i", &team1[4]);

    printf("Team 1 weighs: %i\n", team1);

        return 0;
    }
}

我希望输出打印我在请求用户输入时输入的值,例如“1队的队员有多重?”我的答案是:43、25、64、35。 打印“第 1 队体重:43、25、64、35”。

【问题讨论】:

  • [4] 指的是数组的第五个元素。
  • 是时候了解循环了
  • C 数组索引从零开始。而这个int team1 [] = {110, 113, 112, 117}; 允许您使用从03 的索引。没有team1[4]。导致数组元素越界是未定义的行为。
  • @P.W “第五个元素” Multipass?

标签: c


【解决方案1】:

team1 不是int,它是一个大小为4int 数组。数组“decay”传递给函数时指向指针,这就解释了为什么您会看到该错误消息。

您需要单独打印所有元素,例如使用for 循环。


您的 scanf 调用也不正确 - 您正在读取 team1 数组边界之外的单个元素,这是未定义的行为。您需要使用循环扫描每个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多