Count the number of elements in an array in C [dup

2019-02-10 16:19发布

This question already has an answer here:

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]);

3条回答
看我几分像从前
2楼-- · 2019-02-10 16:31

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.

查看更多
放我归山
3楼-- · 2019-02-10 16:33

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.

查看更多
老娘就宠你
4楼-- · 2019-02-10 16:45

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!
    }
}
查看更多
登录 后发表回答