This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

finding the size of an array before it exists?

What I have is an array of unsigned chars the first byte is actually the number of elements in the array. So is it possible to have the compiler calculate the size of the array using sizeof()? or is there some other way?

#define MENU(ID)                menu_##ID
#define MENU_CNT_P(N)           ((sizeof(MENU(N))-1)/sizeof(menu_position))


This of course gives 0 for the sizeof() value because the array isn't defined.
Suggestions/thoughts welcome.
Stephen

Parents
  • You can use sizeof to determine the size of things (duh). You can determine the total memory for an array using sizeof(array). You can determine the size of a single element in the array using sizeof(array[0]). You can then divide these to get the number of elements in the array as shown below.

    #define ELEMENTS(x) (sizeof((x)) / sizeof((x)[0]))
    
    struct unknown array [] = {1,2,3,4,5,6,7,8 };
    int i;
    .
    .
    .
    for (i=0; i<ELEMENTS(array); i++)
    .
    .
    .
    

    However, in order for sizeof to work, the definition of the array must be visible to the sizeof operator. Otherwise, you have to calculate the number of elements in the array and store the value somewhere. For example:

    #define ELEMENTS(x) (sizeof((x)) / sizeof((x)[0]))
    
    struct unknown array [] = {1,2,3,4,5,6,7,8 };
    int array_elements = ELEMENTS(array);
    

    Then, you don't pollute the array with superfluous data. Also, the content of array_elements is obvious.

    Jon

Reply
  • You can use sizeof to determine the size of things (duh). You can determine the total memory for an array using sizeof(array). You can determine the size of a single element in the array using sizeof(array[0]). You can then divide these to get the number of elements in the array as shown below.

    #define ELEMENTS(x) (sizeof((x)) / sizeof((x)[0]))
    
    struct unknown array [] = {1,2,3,4,5,6,7,8 };
    int i;
    .
    .
    .
    for (i=0; i<ELEMENTS(array); i++)
    .
    .
    .
    

    However, in order for sizeof to work, the definition of the array must be visible to the sizeof operator. Otherwise, you have to calculate the number of elements in the array and store the value somewhere. For example:

    #define ELEMENTS(x) (sizeof((x)) / sizeof((x)[0]))
    
    struct unknown array [] = {1,2,3,4,5,6,7,8 };
    int array_elements = ELEMENTS(array);
    

    Then, you don't pollute the array with superfluous data. Also, the content of array_elements is obvious.

    Jon

Children