2013-03-10 40 views
0
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

你可以发布cal()函数原型 – 2013-03-10 04:06:03

+1

那么,如果我们知道'cal'看起来像什么会有帮助。对不起,太阳耀斑会干扰我们的水晶球。 – 2013-03-10 04:06:45

+1

@NikBougalis好的:) – Ganesh 2013-03-10 04:21:57

回答

4

考虑:

  1. j=cal(res,n,q[i],s);
  2. 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位环境,所有地狱都会破坏疏松。

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


但为什么它给予警告为“可疑指针转换”(而不是预期的消息为“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); 
} 

GCC 4.7.1在64位机器上(和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,所以我已经按照惯例将intlong int中删除了。你说得对,long int是合法的,意思是和一样的东西;大多数人不写多余的字,仅此而已。)

+0

但是,为什么它会发出警告“可疑的指针转换”(如预期的消息所示为“需要L值)? – user2127986 2013-03-10 16:34:28

+0

请参阅答案的更新。 – 2013-03-10 16:45:40

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. 

结论:不要将long long转换为int。你将失去导致错误的数据。转换你的参数来输入long。它可以使用int和long int。