Bohao LI
Bohao LI

Reputation: 2713

pointer to array and two dimensional array in c

struct packet_event *packet_event_p[8];

What does this mean ? Is it a pointer to an array of structure data type (struct packet_event) that has 8 elements ? And how could I make use of this pointer ?

Is it different from :

struct packet_event **packet_event_p;

If yes, how could I use this pointer ?

Upvotes: 1

Views: 83

Answers (3)

Marievi
Marievi

Reputation: 5001

The first declaration :

struct packet_event *packet_event_p[8];

defines an array of 8 elements, each element of which is a pointer to struct packet_event . In other words, you have an array of 8 pointers, and each one points to a struct packet_event.

And how could I make use of this pointer ?

You can allocate memory for a struct packet_event and set a pointer of your array point to it, like this :

struct packet_event *ptr = malloc(sizeof(struct packet_event));
if (ptr == NULL)
    printf ("Error\n");
else
    packet_event_p[0] = ptr;    //choose a pointer packet_event_p[0] - packet_event_p[7]

The second declaration :

struct packet_event **packet_event_p;

is different, as you declare a pointer (and not an array), named packet_event_p, which points to a pointer to struct packet_event.

If yes, how could I use this pointer ?

Allocate memory for the double pointer packet_event_p. See this link for allocating memory for double pointers.

Upvotes: 1

abhishek_naik
abhishek_naik

Reputation: 1297

The first one:

struct packet_event *packet_event_p[8];

stands for 'declare packet_event_p as an array of 8 pointers to struct packet_event'. Thus, you create an array packet_event_p of 8 elements, which are pointers to the struct packet_event. Please see this link.

whereas the second one:

struct packet_event **packet_event_p;

stands for 'declare packet_event_p as pointer to pointer to struct packet_event'. Please see this link.

Hope this is helpful.

Upvotes: 1

Aviv
Aviv

Reputation: 424

It is true that arrays can be decayed to pointers, but they are not the same.

regarding the type it is "Array of 8 pointers to a struct of packed event" reading the types in C usually goes in some sort of a whirlwind fashion. To properly to do, you can read this here.

Usually when you are passing this type as function argument, you will also add the size of the array, or use an external known variable to mark its length. Usually function declarations will be pointers instead of arrays type. I think even that the compiler does automatically (comments about that will be useful)

One different between those types can be seen using the sizeof operator. when applied on variable which is known to be an array type, then the result is the entire size of the array. Otherwise it will be a size of a pointer, which might be 4 byte or 8 byte (depending if its a 64/32bit machine).

Upvotes: 0

Related Questions