Search code examples
carrayspointersmemset

how does this even compile


I just went to look back at old piece of code I've written some time back and saw something like this:

memset(LocRunTimeInfo[LabelId],0x00,sizeof(mpls_RuntimeInfo_t));

should that not instead be:

memset(LocRunTimeInfo + LabelId,0x00,sizeof(mpls_RuntimeInfo_t));

The declartation of LocRunTimeInfo looks like:

static mpls_RuntimeInfo_t *LocRunTimeInfo = NULL;

I have detailed the declaration of mpls_RuntimeInfo_s below:

typedef struct mpls_RuntimeInfo_s {
    UINT16 u16LabelId;
    jpax_egrobstr_t *pEgrObj;
    bcm_l3_intf_t l3_intf;
    bcm_mpls_vpn_config_t vpn_info;
    bcm_gport_t provider_gport;
    bcm_gport_t mpls_p_port_id;
    UINT8 smac[6];
    UINT16 u16ProviderVid;
} mpls_RuntimeInfo_t;

Solution

  • THe first version (LocRunTimeInfo[LabelId]) is missing the address operator: &LocRunTimeInfo[LabelId] would be correct. Without that, it returns struct mpls_RuntimeInfo_s, not the required pointer to it.

    LocRunTimeInfo + LabelId is also correct, as that is identical to the correct version. The text in the standard shows getting the entry itself, but &*(ptr + index) is identical to (ptr + index).

    Note that LocRunTimeInfo should point to an array of sufficient size; the null pointer it has after initialization results in undefined behaviour.