Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the address of the array element in a structure

Tags:

c

How do we get the address of the array element through structure pointer ?

I have an example 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 the rule[0] or as a matter of fact any i.e rule[n] ?

like image 894
user1471 Avatar asked Sep 05 '12 17:09

user1471


1 Answers

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

Yes, it's possible:

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

The same way you can pass a pointer to rules[i] to your function.

like image 54
cnicutar Avatar answered Oct 25 '22 00:10

cnicutar