这可能是由于我缺乏对C的理解,但是在处理数组时出现了一些(我称之为)模糊的错误:
这是代码:
int * generateRandomArray(int numPageReplacements) {
// Seed random number generator
srand(time(NULL));
int * randPages = (int *)malloc(sizeof(int)*numPageReplacements);
for (int i = 0; i < numPageReplacements; i++) {
randPages[i] = rand() % 10; // generate (with uniform distribution) number 0 - 9
printf("%d ", randPages[i]); // for testing purposes
}
printf("\nRandomPages[3] = %d \n" ,randPages[3]);
return randPages; // return array pointer
}
输出:
7 9 4 6 4 6 5 7 6 3
RandomPages[3] = 6
Program ended with exit code: 0
如果我背对背运行(取上面生成的随机数),它有时会给出4(一个人会期望),而在其他情况下会给6(这就像它不知道每个数组单元的边界)。
当我尝试通过调用从此函数获取数组时:
int * ary = generateRandomArray(int numPageReplacements);
printf("Size of ary = %lu",sizeof(ary));
输出:
Size of ary = 8
无论numPageReplacements是什么,它都等于8。
编译器:
Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix
我在这里想念什么吗?
调用sizeof
指针只会给您该指针的大小,这就是实际ary
大小。一个数组将是int ary[10];
您正在使用动态分配的内存,而不是数组。当然,它们就像数组一样工作,因为您可以使用它[]
来访问其元素,但是在幕后,它们却是非常不同的野兽。
众所周知,无法找到数组的大小,甚至根本无法确定数组的大小,而仅int
是传递给函数的单个地址的大小。指针仅存储一个存储器地址。解释该地址的内容取决于程序员。这就是为什么接受数组/缓冲区的C函数始终将数组/缓冲区的大小作为单独的参数的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句