为什么 sizeof() 不是 return 数组的长度?
Why does sizeof() not return the length of an array?
#include <stdio.h>
int main() {
int test[3];
int i;
test[0]=5;
test[1]=10;
test[2]=7;
printf("array size: %d\n",sizeof(test));
sortArray(test);
for(i=0;i<sizeof(test);i++) {
printf(" %d ", test[i]);
}
printf("\n");
}
void sortArray(int number[]) {
int i,j,a;
int n = 5;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (number[j] < number[i]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
}
我遇到问题的数组是 "test"
当我 运行 程序时, "size" 总是预期大小的 4 的倍数。例如:test[3] 会输出 12 的大小。我做错了什么?我也在使用 code::blocks 作为 ide。
sizeof
returns 你传递给它的内存大小。 return 值为...
measured in the number of char-sized storage units required for the
type
在典型的 32 位系统中,char
是一个字节,int
是四个字节,因此对于类型为 int
的数组,您将得到四的倍数.
如果你想要数组的长度,只需除以类型的大小:
int a[3];
size_t n = sizeof(a) / sizeof(a[0]);
注意:正如下面评论中dbush提到的:
...this only works if the array is not a paramerer to a
function. In that case the array decays to a pointer and sizeof(array)
evaluates to the size of a pointer.
#include <stdio.h>
int main() {
int test[3];
int i;
test[0]=5;
test[1]=10;
test[2]=7;
printf("array size: %d\n",sizeof(test));
sortArray(test);
for(i=0;i<sizeof(test);i++) {
printf(" %d ", test[i]);
}
printf("\n");
}
void sortArray(int number[]) {
int i,j,a;
int n = 5;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (number[j] < number[i]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
}
我遇到问题的数组是 "test" 当我 运行 程序时, "size" 总是预期大小的 4 的倍数。例如:test[3] 会输出 12 的大小。我做错了什么?我也在使用 code::blocks 作为 ide。
sizeof
returns 你传递给它的内存大小。 return 值为...
measured in the number of char-sized storage units required for the type
在典型的 32 位系统中,char
是一个字节,int
是四个字节,因此对于类型为 int
的数组,您将得到四的倍数.
如果你想要数组的长度,只需除以类型的大小:
int a[3];
size_t n = sizeof(a) / sizeof(a[0]);
注意:正如下面评论中dbush提到的:
...this only works if the array is not a paramerer to a function. In that case the array decays to a pointer and sizeof(array) evaluates to the size of a pointer.