ç的sizeof一个传递的数组 [英] C sizeof a passed array
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array\">How找到的sizeof(指针指向一个数组)
块引用>据我所知,sizeof操作符进行评估,并在编译时常数取代。鉴于此,怎么能一个功能,而在不同的点在程序中通过不同的阵列,有它的尺寸计算的?我可以把它作为一个参数的功能,但我宁愿没有添加其他的参数,如果我没有绝对要。
下面是说明我在问什么一个例子:
的#include&LT;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;的#define SIZEOF(一)(sizeof的一个/ sizeof的一个[0])
无效printarray(双X [],int);在诠释的main()
{
双ARRAY1 [100];
的printf(的数组1 =%LD \\ n的大小。SIZEOF(数组1));
的printf(N的数组1 =%LD \\的大小。,sizeof的数组1);
的printf(数组1的大小[0] =%LD \\ n \\ n,sizeof的ARRAY1 [0]); printarray(数组1,SIZEOF(数组1)); 返回EXIT_SUCCESS;
}
无效printarray(双P [],int类型)
{
INT I;
//这是没有按T工作,所以其结果是,我通过
//大小作为第二个参数,这是我最好不做。
的printf(的对计算值=%LD \\ n的大小。SIZEOF(P));
的printf(的P =%LD \\ n的大小。,sizeof的P);
的printf(P [0] =%大小LD \\ n,sizeof的P [0]); 对于(i = 0; I&LT; S;我++)
的printf(%Eelement:D =%LF \\ n,I,P [I]); 返回;
}
解决方案有没有神奇的解决方案。 C不是反射语言。对象不自动知道它们是什么。
但是,你有很多选择:
- 显然,添加参数
- 编写一个宏来包装调用,并自动添加参数
- 使用更复杂的对象。定义包含动态数组,也数组的大小的结构。然后,通过结构的地址。
Possible Duplicate:
How to find the sizeof( a pointer pointing to an array )I understand that the sizeof operator is evaluated and replaced with a constant at compile time. Given that, how can a function, being passed different arrays at different points in a program, have it's size computed? I can pass it as a parameter to the function, but I'd rather not have to add another parameter if I don't absolutely have to.
Here's an example to illustrate what I'm asking:
#include <stdio.h> #include <stdlib.h> #define SIZEOF(a) ( sizeof a / sizeof a[0] ) void printarray( double x[], int ); int main() { double array1[ 100 ]; printf( "The size of array1 = %ld.\n", SIZEOF( array1 )); printf( "The size of array1 = %ld.\n", sizeof array1 ); printf( "The size of array1[0] = %ld.\n\n", sizeof array1[0] ); printarray( array1, SIZEOF( array1 ) ); return EXIT_SUCCESS; } void printarray( double p[], int s ) { int i; // THIS IS WHAT DOESN"T WORK, SO AS A CONSEQUENCE, I PASS THE // SIZE IN AS A SECOND PARAMETER, WHICH I'D RATHER NOT DO. printf( "The size of p calculated = %ld.\n", SIZEOF( p )); printf( "The size of p = %ld.\n", sizeof p ); printf( "The size of p[0] = %ld.\n", sizeof p[0] ); for( i = 0; i < s; i++ ) printf( "Eelement %d = %lf.\n", i, p[i] ); return; }
解决方案There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.
But you have many choices:
- Obviously, add a parameter
- Write a macro to wrap the call, and automatically add a parameter
- Use a more complex object. Define a structure which contains the dynamic array and also the size of the array. Then, pass the address of the structure.
这篇关于ç的sizeof一个传递的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!