采取long int的可疑指针转换

时间:2013-03-10 04:03:19

标签: c

int main()
{
    long int i,t,n,q[500],d[500],s[500],res[500]={0},j,h;
    scanf("%ld",&t);
    while(t--)
    {
        scanf("%ld %ld",&n,&h);
        for(i=0;i<n;i++)
            scanf("%ld %ld",&d[i],&s[i]);
        for(i=0;i<h;i++)
            scanf("%ld",&q[i]);
        for(i=0;i<h;i++)
        {
            for(j=0;j<n;j++)
            {
                res[j]=d[j]+q[i]*s[j];
            }
        j=cal(res,n,q[i],s);
        printf("%ld\n",j);
        }
    }
    return 0;
}

long int cal(int res[],int n,int q,int s[])
{
    long int i,max=0,p,pos=0;
    for(i=0;i<n;i++)
    {
        if (max==res[i])
        {
            pos=add(res,s,pos,i,q);
            max=res[pos];
        }
        if (res[i]>max)
        {
                max=res[i];
                pos=i;
        }
    }
    return pos;
}

每当我将变量变为int时,它工作正常,但如果我将变量声明为long int,我会在函数调用中收到警告消息“可疑指针转换” - 在行:

(j=cal(res,n,q[i],s));

你能解释一下原因吗?

2 个答案:

答案 0 :(得分:4)

假设:

  1. long int i,t,n,q[500],d[500],s[500],res[500]={0},j,h;
  2. j=cal(res,n,q[i],s);
  3. long int cal(int res[],int n,int q,int s[])
  4. 您正在尝试将数组long res[500]传递给期望数组为int的函数。即使机器上的sizeof(int) == sizeof(long),类型也不同 - 我的机器上的尺寸肯定不同。

    如果您使用的是Windows(32位或64位)或32位Unix,那么您可以使用它,但如果您迁移到LP64 64位环境,那么一切都将破坏

    这就是为什么它是'可疑的指针转换'。它不是犹太人;它不可靠;它恰好适用于您的环境(但出于可移植性的原因,它非常可疑)。


      

    但为什么它会发出“可疑指针转换”的警告(而不是预期的消息为“需要L值”)?

    我不确定为什么会出现l-value required错误。请记住,当你调用一个函数时,数组会衰减为指针,所以你的函数声明也可以写成long cal(int *res, int n, int q, int *s),并且你传递long res[500],它会自动更改为long *(就像你写了&res[0]),所以你传递的long *预计会有int *,你可能会侥幸逃脱它(因此'可疑'而不是任何东西更严重的。)

    考虑代码:

    long res[500];
    long cal(int res[]);
    
    int main(void)
    {
        return cal(res);
    }
    

    64位计算机(和64位编译)上的GCC 4.7.1说:

    x.c: In function ‘main’:
    x.c:6:5: warning: passing argument 1 of ‘cal’ from incompatible pointer type [enabled by default]
    x.c:2:6: note: expected ‘int *’ but argument is of type ‘long int *’
    

    (我经常看到有人写long int而不只是long,所以我采用了int long int的常规做法你是正确的long int是有效合法的,与long意思相同;大多数人都没有写出额外的词,就是全部。)

答案 1 :(得分:0)

ISO C 9899在算术操作数

下的6.3.1.1中说
The rank of long long int shall be greater than the rank of long int, which
shall be greater than the rank of int, which shall be greater than the rank of short
int, which shall be greater than the rank of signed char

KnR ANSI C版本以2.2数据类型和大小说明

short is often 16 bits long, and int either 16 or 32 bits. Each compiler is free to     choose appropriate sizes for its own
hardware, subject only to the the restriction that shorts and ints are at least 16     bits, longs are
at least 32 bits, and short is no longer than int, which is no longer than long.

结论:不要长期投入到int。您将丢失导致错误的数据。将您的参数转换为long类型。它可以采用int和long int。

相关问题