2011-01-21 43 views
-1
int Myfunc2(int array[]) 
{ 
    //however the length of array is different in 2 compiler here. 
    //it is a zero terminated array. but when passed into Myfunc2, array's second 
    //elements becomes 0; 
    do_something(array); 
} 

struct A 
{ 
    int a; 
    int b[5]; 
}; 
int Myfunc1() 
{ 
    struct A st; 
    Init(&st); 
    Myfunc2((&st)->b); 
} 

Myfunc2使用p指向的数组中的第二个元素。C问题:2编译器之间的差异

在visual studio中,它是一个以原始大小传递的数组。而在海湾合作委员会的阵列是 大小1.哪一个是正确的?

+5

咦?你能解释一下吗? – 2011-01-21 15:39:07

+0

是的,请澄清。 – 2011-01-21 15:43:39

回答

0

当声明一个函数接受一个数组时,它将被静默地转换为接受指向第一个元素的指针。因此,您的代码int Myfunc2(int array[]);将自动变为int Myfunc2(int *array);

没有将数组长度信息传递给被调用的函数。您能否请将代码发布到Myfunc2()向我们展示您如何试图获取这些信息?

0

C和C++没有“数组长度”的概念。您可以在声明的范围内使用sizeof()运算符除以sizeof()数据类型静态定义的数组上。

如果您需要需要来了解std :: vector的大小,可能会有更好的用例。或者,同样轻松地将数组的长度传递给函数。

评论:您仍然没有提供足够的信息来评估函数2的功能,以及您如何获得阵列的长度。没有显示这一点,你不会得到很好的答案。

编辑:在gcc中,这为我打印4。总是。我重复;因为某种原因,没有更多的信息,就像是你的孙子与野生动物打架一样,你的问题不会得到回答。

#include <iostream> 

using namespace std; 

int Myfunc2(int array[]) 
{ 
    int length = 0; 
    while(array[length] != 0) length++; 

    return length; 
} 

void Init(A * st) 
{ 
    st->a = 0; 
    for(int i = 1; i < 5; i++) 
    { 
    st->b[i-1] = i; 
    } 

    st->b[4] = 0; 
} 

int Myfunc1() 
{ 
    A st; 
    Init(&st); 
    cout << Myfunc2(st.b); 
} 

int main() 
{ 
    Myfunc1(); 
}