gpt4 book ai didi

c - 采取 long int 时的可疑指针转换

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:43 25 4
gpt4 key购买 nike

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));

能解释一下原因吗?

最佳答案

给定:

  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[])

您正在尝试将数组 long res[500] 传递给需要 int 数组的函数。即使 sizeof(int) == sizeof(long) 在您的机器上,类型也不同 — 而且大小在我的机器上肯定不同。

如果你在 Windows(32 位或 64 位)或 32 位 Unix 上,你会摆脱它,但如果你迁移到 LP64 64 位环境,一切都会崩溃.

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


But why is it giving a warning as "suspicious pointer conversion" (instead of the expected message as "L-Value required")?

我不确定您为什么期望出现 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 位机器上的 GCC 4.7.1(和 64 位编译)说:

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 from long int. 你是对的,long int 是合法的并且和 long 是一样的;大多数人不会写多余的字,仅此而已。)

关于c - 采取 long int 时的可疑指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15318787/

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