这可能是由于我对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
}
Run Code Online (Sandbox Code Playgroud)
输出:
7 9 4 6 4 6 5 7 6 3
RandomPages[3] = 6
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)
如果我背对背地运行(取上面生成的随机数),它有时会给出4(人们期望的)和其他的6(这就像它不知道每个数组单元的边界一样).
当我尝试从调用中获取此函数的数组时:
int * ary = generateRandomArray(int numPageReplacements);
printf("Size of ary = %lu",sizeof(ary));
Run Code Online (Sandbox Code Playgroud)
输出:
Size of ary = 8
Run Code Online (Sandbox Code Playgroud)
无论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函数总是将该数组/缓冲区的大小作为单独的参数.