如何确定C语言中数组的大小?
也就是说,数组可以容纳多少元素?
如何确定C语言中数组的大小?
也就是说,数组可以容纳多少元素?
当前回答
要知道在代码中显式声明并由其变量引用的固定数组的大小,可以使用sizeof,例如:
int a[10];
int len = sizeof(a)/sizeof(int);
但这通常是没有用的,因为你已经知道答案了。
但如果你有一个指针,你不能使用sizeof,这是一个原则问题。
但是…由于数组是作为线性内存提供给用户的,如果您知道最后一个元素地址,并且如果您知道类型的大小,那么您就可以计算它有多少个元素。例如:
#include <stdio.h>
int main(){
int a[10];
printf("%d\n", sizeof(a)/sizeof(int));
int *first = a;
int *last = &(a[9]);
printf("%d\n", (last-first) + 1);
}
输出:
10
10
另外,如果你不能利用编译时,你可以:
#include <stdio.h>
int main(){
int a[10];
printf("%d\n", sizeof(a)/sizeof(int));
void *first = a;
void *last = &(a[9]);
printf("%d\n", (last-first)/sizeof(int) + 1);
}
其他回答
“你这是搬起石头砸自己的脚。”
C 'native'数组不存储它们的大小。因此,建议将数组的长度保存在单独的变量/const中,并在传递数组时传递它,即:
#define MY_ARRAY_LENGTH 15
int myArray[MY_ARRAY_LENGTH];
如果你正在编写c++,无论如何你都应该避免本机数组(除非你不能,在这种情况下,小心脚下)。如果你正在编写c++,请使用STL的“vector”容器。“与数组相比,它们提供了几乎相同的性能”,而且它们更有用!
// vector is a template, the <int> means it is a vector of ints
vector<int> numbers;
// push_back() puts a new value at the end (or back) of the vector
for (int i = 0; i < 10; i++)
numbers.push_back(i);
// Determine the size of the array
cout << numbers.size();
看到的: http://www.cplusplus.com/reference/stl/vector/
你可以使用&操作符。以下是源代码:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10];
int *p;
printf("%p\n", (void *)a);
printf("%p\n", (void *)(&a+1));
printf("---- diff----\n");
printf("%zu\n", sizeof(a[0]));
printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));
return 0;
};
下面是示例输出
1549216672
1549216712
---- diff----
4
The size of array a is 10
一个更优雅的解决方案是
size_t size = sizeof(a) / sizeof(*a);
要知道在代码中显式声明并由其变量引用的固定数组的大小,可以使用sizeof,例如:
int a[10];
int len = sizeof(a)/sizeof(int);
但这通常是没有用的,因为你已经知道答案了。
但如果你有一个指针,你不能使用sizeof,这是一个原则问题。
但是…由于数组是作为线性内存提供给用户的,如果您知道最后一个元素地址,并且如果您知道类型的大小,那么您就可以计算它有多少个元素。例如:
#include <stdio.h>
int main(){
int a[10];
printf("%d\n", sizeof(a)/sizeof(int));
int *first = a;
int *last = &(a[9]);
printf("%d\n", (last-first) + 1);
}
输出:
10
10
另外,如果你不能利用编译时,你可以:
#include <stdio.h>
int main(){
int a[10];
printf("%d\n", sizeof(a)/sizeof(int));
void *first = a;
void *last = &(a[9]);
printf("%d\n", (last-first)/sizeof(int) + 1);
}
#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))