#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_PARMS 20
#define DATA_MAX 50
struct s {
uint8_t cmd;
uint8_t main;
uint8_t sub;
uint8_t index;
uint8_t reg;
uint8_t sendlen;
uint8_t reclen;
uint8_t parm[MAX_PARMS];
};
struct t {
uint8_t hdr;
uint8_t data[DATA_MAX];
uint8_t len;
};
int main()
{
struct t *p = malloc(sizeof(struct t));
p->data[0] = 0xBC;
p->data[1] = 0xDE;
p->data[2] = 0xFF;
p->data[3] = 0x01;
struct s *testCmd1 = (struct s *) &p->data;
struct s *testCmd2 = (struct s *) p->data;
printf("0x%02x 0x%02x 0x%02x\n", p->data[0], testCmd1->cmd, testCmd2->cmd);
printf("0x%02x 0x%02x 0x%02x\n", p->data[1], testCmd1->main, testCmd2->main);
printf("0x%02x 0x%02x 0x%02x\n", p->data[2], testCmd1->sub, testCmd2->sub);
printf("0x%02x 0x%02x 0x%02x\n", p->data[3], testCmd1->index, testCmd2->index);
return 0;
}
Running the code above prints out:
0xbc 0xbc 0xbc
0xde 0xde 0xde
0xff 0xff 0xff
0x01 0x01 0x01
I am wondering why &p->data and p->data seem to get resolved to the same address.
It seems to me like &p->data should be a pointer to the address of data[0], while p->data would be simply the address of data[0]. I would get weird values printing out for one of them if that were the case though, correct?
Ideally, I don't think I would use code like this, but I ran across it in someone elses code and this was a test I wrote to see what was going on.
If this question has already been answered, I couldn't find it, apologies if that is the case.