سؤال

I'm having problem getting the actual size of an int-type array.

Note: I got no problem with char-type arrays, I got the output I expect.

Example, having this declaration, int arr[3] and using sizeof(arr) will have an output that will surely vary, it could be 3, 6, 12, etc... depending on the bit-system.
So how will then I get the actual size of my array on a code like this: Ideone Code Here

#include <stdio.h>
int countSize[3]={1,2,3};

int main() {
    printf("%d",sizeof(countSize));
    return 0;
}
هل كانت مفيدة؟

المحلول

Looks like by actual size, you mean the elements of the array. Since sizeof(countSize) gives the size of the array in bytes, all you need is to divide it by the size of each element like this:

printf("%zu\n", sizeof(countSize) / sizeof(int));

Or better, use sizeof(countSize[0] as the type of the array may vary:

printf("%zu\n", sizeof(countSize) / sizeof(countSize[0]));

You got expected result when working with char arrays because sizeof(char) is always 1.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top