问题
How can I obtain the number of elements present in an integer array in C after the array is passed to a function? The following code doesn't work.
size=sizeof(array)/sizeof(array[0]);
回答1:
In C, you can only get the size of statically allocated arrays, i.e.
int array[10];
size = sizeof(array) / sizeof(int);
would give 10.
If your array is declared or passed as int* array
, there is no way to determine its size, given this pointer only.
回答2:
You are most likely doing this inside the function to which you pass the array.
The array decays as pointer to first element So You cannot do so inside the called function.
Perform this calculation before calling the function and pass the size as an function argument.
回答3:
You are going about it in the wrong way. I'll try to explain using a small code example. The explanation is in the code comments:
int array[100];
int size = sizeof(array) / sizeof(array[0]); // size = 100, but we don't know how many has been assigned a value
// When an array is passed as a parameter it is always passed as a pointer.
// it doesn't matter if the parameter is declared as an array or as a pointer.
int getArraySize(int arr[100]) { // This is the same as int getArraySize(int *arr) {
return sizeof(arr) / sizeof(arr[0]); // This will always return 1
}
As you can see from the code above you shouldn't use sizeof
to find how many elements there are in an array. The correct way to do it is to have one (or two) variables to keep track of the size.
const int MAXSIZE 100;
int array[MAXSIZE];
int size = 0; // In the beginning the array is empty.
addValue(array, &size, 32); // Add the value 32 to the array
// size is now 1.
void addValue(int *arr, int *size, int value) {
if (size < MAXSIZE) {
arr[*size] = value;
++*size;
} else {
// Error! arr is already full!
}
}
来源:https://stackoverflow.com/questions/15929869/count-the-number-of-elements-in-an-array-in-c