Count the number of elements in an array in C [duplicate]

这一生的挚爱 提交于 2019-11-30 14:57:09

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.

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.

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!
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!