Reputation: 466
I have an array of simple structures declared in my code. A
sizeof()
response is being returned that does not match the size of the array. Is there some other way that this should be declared to ensure the correct sizeof response?
struct control_cmd {
const char * cmd;
void (*cmd_fn)(int,char *(*)[],char*);
};
struct control_cmd control_cmds[]={
{"ANNOUNCE",control_announce},
{"SEND",control_send}
};
sizeof(control_cmds)
returns a value of 16
when I am expecting a value of 2
.
What's going on?
Upvotes: 0
Views: 90
Reputation: 1545
I would typedef control_cmd_t
, declare control_cmds
as an array of control_cmd_t
, and divide the two. (Very similar to Arkku's answer).
#include <stdio.h>
typedef struct control_cmd_t__ {
const char * cmd;
void (*cmd_fn)(int,char *(*)[],char*);
} control_cmd_t;
control_cmd_t control_cmds[]={
{"ANNOUNCE",control_announce},
{"SEND",control_send}
};
int main()
{
printf("sizeof control_cmd_t is: %ld\n", sizeof(control_cmd_t));
printf("sizeof control_cmds is: %ld\n", sizeof(control_cmds));
printf("number of elements in control_cmds is: %d", (sizeof(control_cmds)/sizeof(control_cmd_t)));
return 0;
}
Output:
sizeof control_cmd_t is: 16
sizeof control_cmds is: 32
number of elements in control_cmds is: 2
Upvotes: 1
Reputation: 42129
sizeof
is the size in memory, not the number of elements. In case of an array (not a pointer!) you can obtain the number of elements by dividing the size of the array by the size of a single element, i.e., sizeof(control_cmds) / sizeof(*control_cmds)
.
Upvotes: 2