Get the address of an array element in a structure

How to get the address of an array element through a structure pointer?

I have a sample code as follows:

#include<stdio.h> #include<string.h> typedef struct { int mynam ; } transrules; typedef struct { int ip ; int udp; transrules rules[256]; }__attribute__ ((__packed__)) myudp; myudp udpdata ; myudp* ptrudp = &udpdata ; int main(){ memset (&udpdata , 0 ,sizeof(udpdata)); ptrudp->ip = 12 ; ptrudp->udp = 13 ; ptrudp->rules[0].mynam = 15 ; printf("%d",ptrudp->rules[0].mynam); return 0; } 

My function wants the address of the rules [0] to be passed as an argument. Is it possible to print the address of rule [0] or, in fact, any rule [n]?

+4
source share
3 answers

Is it possible to print the address of the rule [0] or as a matter of fact the fact of any rule I [n]

Yes, it is possible:

 printf("%p\n", (void *) &ptrudp->rules[i]); /* Cast required by %p. */ 

Similarly, you can pass a pointer to rules[i] in your function.

+4
source

A pointer to a structure indicates a structure, so the address of the element is still available.

 f(&ptrudp->rules[n]); 
0
source

Yes. You get access to it, as usual, with any other array, just take it from the structure using the operator -> :

 transrules *addr = &ptrudp->rules[n]; 
0
source

Source: https://habr.com/ru/post/1432535/


All Articles