How to determine how many elements there are in an array of compound literals in C?

StackOverflow https://stackoverflow.com/questions/17279341

  •  01-06-2022
  •  | 
  •  

Domanda

How can I determine how many elements there are in an array of compound literals. I'm using the well known macro sizeof(a)/sizeof(a[0]); but keep getting 1.

#include <stdio.h>
typedef struct {
    int enable;
    const char * const *message;
} table_s;

static const table_s table[] =
{
    { 1, (const char * const []){ "Message 1", "Message 2"   } },
    { 1, (const char * const []){ "Message 1", "Message 2", "Message 3"} }
};

#define NELEMS(x)  (sizeof(x) / sizeof(x[0]))
int main(int argc, char *argv[]) {
    printf("%d\n", NELEMS(table[0].message));
    printf("%d\n", NELEMS(table[1].message));
    return 0;
}
È stato utile?

Soluzione

sizeof(a)/sizeof(*a) will only work if a is a compile time dynamic size block and is typed as such.

char * messages[] = { "Message 1", "Message 2", "Message 3"};

sizeof(messages)/sizeof(*messages) = sizeof((char *)[3]) / sizeof(char*) = 3

But in your case you are operating on a pointer type

  NELEMS(table[0].message) 
= sizeof(table[0].message) / sizeof(table[0].message[0]) 
= sizeof(const char * const *)/sizeof(const char * const) 
= sizeof(void *) / sizeof(void *) = 1

Altri suggerimenti

You can not do that in C cause of the way a C array works.

let's say you have int a[100];

a is just a pointer to the area of the memory where the elements are put one after the other.

In this example the size on bytes of an int is 4. The size of a pointer to int (int*) is also 4 bytes.

a is a variable which only stores a mem dress like 0x0000866A

and in mem starting at that address you will find:

a[0]_on_first_4_bytes|a[1]_next_4_bytes|a[2]_next_4_bytes concatenated one near the other.

But since the size of (int*) = size of (int) => Size of a = size of a[0] .

Unless you store somewhere the number of elements you can't find it otherwise.

The "well known macro" only works with arrays and not with pointers.

What you are doing is taking the size of a pointer to a pointer and dividing it by the size of a pointer. Pointers to data of any type are almost always the same size. This is why you are getting 1 as your result.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top