关于将指针作为参数传递

时间:2018-09-30 17:12:40

标签: c pointers

我正在尝试编写基本的零阈值函数。这样,如果数组元素的值大于零,则必须保持相同,否则必须为零。但是我的问题是使用指针将数组值从main传递到函数。这是代码段。 im是输入数组,im2是用于存储结果的数组。 t是阈值,为0,m是顺序。将输入数组从main传递给thresh函数。我只是检查了thresh函数中im的值,但是所有值都显示为0(如下面的代码所述),而不是原始值。我要去哪里错了?

int thresh(double *im[], double *im2[], int t, int m)
{
    int i, j;
    printf("im:%f", im[0]); //here i am getting output as zero instead of 1
    for (i = 0; i < m; i++)
    {
        if (im[i] > t)
            im2[i] = im[i];
        else
            im2[i] = 0;
    }
    return 0;
}

int main()
{
    float im[4] = { 1,-2,3,-4 };
    float im2[4];
    int th = 0;
    thresh((float*)im, (float*)im2, th, 2);

    getch();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

打开编译器警告并阅读它们。他们在那里为您提供帮助。这是我在编译时得到的:

$ gcc main.c 
main.c: In function ‘thresh’:
main.c:10:23: warning: comparison between pointer and integer
             if (im[i] > t)
                       ^
main.c: In function ‘main’:
main.c:24:12: warning: passing argument 1 of ‘thresh’ from incompatible pointer type [-Wincompatible-pointer-types]
     thresh((float*)im, (float*)im2, th, 2);
            ^
main.c:4:5: note: expected ‘double **’ but argument is of type ‘float *’
 int thresh(double *im[], double *im2[], int t, int m)
     ^~~~~~
main.c:24:24: warning: passing argument 2 of ‘thresh’ from incompatible pointer type [-Wincompatible-pointer-types]
     thresh((float*)im, (float*)im2, th, 2);
                        ^
main.c:4:5: note: expected ‘double **’ but argument is of type ‘float *’
 int thresh(double *im[], double *im2[], int t, int m)
     ^~~~~~

所以有一些东西要修复。

首先,thresh的原型应该是int thresh(double *im, double *im2, int t, int m)甚至更好的int thresh(const double *im, double *im2, int t, int m)

第二,为什么要混合使用floatdouble?坚持一个,坚持double,除非您有充分的理由。