你能解释一下
例如:
sizeof()
如何与随机长度的数组一起使用吗?我以为对于数组来说,sizeof()
是在编译时计算的,但是,具有随机长度的数组的大小似乎被正确地计算了。例如:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
srand ( (unsigned)time ( NULL ) );
int r = rand()%10;
int arr[r]; //array with random length
printf("r = %d size = %d\n",r, sizeof(arr)); //print the random number, array size
return 0;
}
多次运行后的输出结果:r = 8 size = 32
r = 6 size = 24
r = 1 size = 4
编译器:gcc 4.4.3
int arr[r];
这一行代码,我真的不知道它是如何编译通过的。我以为栈中的数组在编译期间必须要知道它们的大小。 - oriprand() % 10
恰好为0,则行为未定义。C语言不支持零大小的数组(尽管gcc可能作为扩展支持)。 - Keith Thompson