I have a question about the size of the C array

Asked 2 years ago, Updated 2 years ago, 60 views

How do I figure out how many elements can fit in an array in C?

I want to know the maximum possible elements, not the size of the array.

c array memory

2022-09-21 18:36

1 Answers

To sum it up beforehand, sizeof(array name)/sizeof(element of array) You can get it by .

sizeof returns the overall size of the array. For example,

int main() {
    /*Arrays of 10 elements*/
    char charArr[10];
    int intArr[10];
    long longArr[10];
    double doubleArr[10];

    printf("sizeof(char)\t:%lu,\tsizeof(charArr):\t%lu\n", sizeof(char), sizeof(charArr));
    printf("sizeof(int)\t\t:%lu,\tsizeof(intArr):\t\t%lu\n", sizeof(int), sizeof(intArr));
    printf("sizeof(long)\t:%lu,\tsizeof(longArr):\t%lu\n", sizeof(long), sizeof(longArr));
    printf("sizeof(double)\t:%lu,\tsizeof(doubleArr):\t%lu\n", sizeof(double), sizeof(doubleArr));

}

Output:

sizeof(char)    :1, sizeof(charArr):    10
sizeof(int)     :4, sizeof(intArr):     40
sizeof(long)    :8, sizeof(longArr):    80
sizeof(double)  :8, sizeof(doubleArr):  80

Can you see the relationship between sizeof(type) and sizeof(array) here? Everyone has declared an array of 10 elements, and sizeof is exactly 10 times the sizeof.

Therefore, the number of elements in the array can be obtained as sizeof/sizeof.

However, it is always troublesome to specify the type of elements in the array, such as sizeof(int) or sizeof(long), and when the casting changes, the code must be fixed, so it is usually written like sizeof(charArr[0]).

For example,

int main() {
    inta[100]; //number of elements 100
    printf("sizeof(arrangement name): %lu\n", sizeof(a)); //400
    printf("sizeof" element: %lu\n", sizeof(a[0]); //4
    printf("number of elements = sizeof(array name)/sizeof(element of array): %lu\n", sizeof(a)/sizeof(a[0])); //100
}

Output:

sizeof (array name): 400
size of (element of array): 4
Number of elements = sizeof(arrangement name)/sizeof(element of arrangement): 100

If you're lazy to divide every time you get an array size, define and write a macro as follows.

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
int n = NELEMS(a);


2022-09-21 18:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.