【发布时间】:2021-08-05 04:11:11
【问题描述】:
可能重复:
How to find the sizeof( a pointer pointing to an array )
我了解 sizeof 运算符在编译时被评估并替换为常量。鉴于此,在程序的不同点传递不同数组的函数如何计算其大小?我可以将它作为参数传递给函数,但如果我不是绝对必须添加另一个参数,我宁愿不必添加其他参数。
这里有一个例子来说明我在问什么:
#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;
}
【问题讨论】:
-
Standard C gotcha -- 查看链接到的问题。
-
sizeof在 C99 中不必在编译时进行评估 - VLA 可以与sizeof一起正常工作,并且它们的大小只能在运行时知道。