gpt4 book ai didi

c - 为什么我在尝试传递数组值时收到 "incompatible pointer type"?

转载 作者:行者123 更新时间:2023-11-30 16:05:58 25 4
gpt4 key购买 nike

尝试从主函数中的点获取最小值/最大值时收到错误/警告。如何计算最大/最小点?有没有更简单的方法?我应该使用结构吗?

        test.c:73:14: warning: incompatible pointer types passing 'int [100][100]' to      parameter of type 'int *' [-Wincompatible-pointer-types]      convexHull(points, n);        test.c:33:21: note: passing argument to parameter 'point' here        void convexHull(int point[], int n)                    ^        1 warning generated.**
void convexHull(int point[], int n)
{
int i;
//n is the size
int min_x=0;
int max_x=0;

if (n <3)
{
printf("Convex hull can't have less than 3 points\n.");
}

//Finding point with min/max x-coordinate.
for (i=1;i<n;i++)
{
if (point[i] < point[min_x])
{
min_x=i;
}
if (point[i] > point[max_x])
{
max_x = i;
}
}
printf("%d\n",max_x);
printf("%d\n",min_x);
}

int main()
{
int n;
int points[100][100] = {{0, 3}, {2, 2}, {1, 1}, {2, 1},
{3, 0}, {0, 0}, {3, 3}};

n = sizeof(points)/sizeof(points[0]);
convexHull(points, n);


return 0;
}

最佳答案

数组 points被声明为二维数组

  int points[100][100] = {{0, 3}, {2, 2}, {1, 1}, {2, 1},
{3, 0}, {0, 0}, {3, 3}};

因此在表达式中用作函数参数时,它会隐式转换为指向 int ( * )[100] 类型的第一个元素的指针.

但是相应的函数参数的类型为 int *

void convexHull(int point[], int n)

因为参数声明为int point[]由编译器调整为声明 int * point .

并且没有从类型 int ( * )[100] 进行隐式转换输入 int * .

而且看来这个声明

  int points[100][100] = {{0, 3}, {2, 2}, {1, 1}, {2, 1},
{3, 0}, {0, 0}, {3, 3}};

没有意义,因为每个“点”只有 twp 元素,例如 {0, 3}但不是 100 个元素。

您需要声明一个结构,例如

struct Point
{
int x;
int y;
};

并在您的程序中使用它。

在这种情况下,可以通过以下方式定义点数组

  struct Point points[] = { {0, 3}, {2, 2}, {1, 1}, {2, 1},
{3, 0}, {0, 0}, {3, 3} };

因此函数声明和定义应相应更改。

关于c - 为什么我在尝试传递数组值时收到 "incompatible pointer type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60101860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com