문제

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