Accessing structure members using base address

pointer to structure array
pointer to structure c++
pointer to structure in c pdf
address of structure member in c
structure pointer function in c
structure pointer in c tutorialspoint
structure assignment in c
c pointer to struct member

Can you please help explain why following program correctly prints the values of all the structure members?

struct st
{
  int i;
  char c1;
  int j;
  char c2;
};

int main()
{
  struct st a = {5, 'i', 11, 'H'};
  struct st * pa = &a;

  int first;
  char second;
  int third;
  char fourth;

  first = *((int*)pa);
  second = *((char*)pa + 4); /* offset = 4 bytes = sizeof(int) */
  third = *((int*)pa + 2); /* why (pa + 2) here? */
  fourth = *((char*)pa + 12); /* why (pa + 12) here? */
  printf ("first = %d, second = %c, third = %d, fourth = %c\n", first, second, third, fourth);
  return 0;
}

Output: first = 5, second = i, third = 11, fourth = H

How can I make above program generalized?

That's because of the padding bytes added to the structure. Three padded bytes will be added after char second;, this is because the char is followed by an int (member with larger alignment) so padding bytes will be inserted to make the alignment multiple of the alignment of larger member.

C accessing structure members - C Programming, member, to ensure correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes. Which says you can access one of the integers in the structure relative to the starting address of one of the structures. e.g: B b; B *pb = &b; pb->*p = 100; The last statement sets the i member of b to be 100, indirectly.

How can I make above program generalized?

The only way to make it work reliably is by not guessing at the offset. Use the standard offsetof macro, and always do the pointer arithmetic with a character pointer:

first = *(int*)((char*)pa + offsetof(struct st, i));

You don't have to name the field at the point you do the access, but you should definitely use the macro to compute the offest if you intend to pass it into your function.

C structs and Pointers (With Examples), Person { char name[50]; int citNo; float salary; } person1, person2, p[20]; Accessing structure member through pointer using dynamic memory allocation. To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under “stdlib.h” header file. Syntax to use malloc() ptr=(cast-type*)malloc(byte-size) Example to use structure’s member through pointer using malloc() function.

It is because of structure padding.

After padding your structure will look like below.

struct st
{
  int i;
  char c1;
  char padding[3]; // for alignment of j.
  int j;
  char c2; 
  char padding[3]; // for alignment of structure.
};

Hence

first = *((int*)pa);
  second = *((char*)pa + 4); /* offset = 4 bytes = sizeof(int) */
  third = *((int*)pa + 2); /* offset = 8 bytes(pointer arithmetic) to point to int j*/
  fourth = *((char*)pa + 12); /* offset = 12 bytes to point to char c2*/

For more info on structure padding read Data_structure_alignment

Struct memory layout in C, I know the way to access the members of structure using . or -> operator. I can access members of array using base pointer for example: Hide  Accessing Structure Members. To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type.

As in another answers - padding.

But some compilers allow you to pack your structures removing (in most cases) the padding.

gcc:

struct __attribute__((packed)) st
{
....
}

The code which access the packed structs may be less efficient and longer.

C struct (Structures), Example: Access members using Pointer. To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the  In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1;. Now, you can access the members of person1 using the personPtr pointer. By the way, personPtr->age is equivalent to (*personPtr).age. personPtr->weight is equivalent to (*personPtr).weight.

When creating a struct, all variables occupy the same amount of space (32 bits), the remaining unused bits are padding. So even if you define a char in the struct, this will occupy 4 bytes. This is due to the fact that your processor addresses data at 32 bits, even if afterwards less bits are used. The memory on the other side stores 1 byte for each address, but when data is fetched by the CPU, data will be adapted to the bus architecture (that depends on the processor).

Also note that the offset depends on the pointer you are using. a char* in this case will increase by 1, while a int* by 4.

This also means that the code is not portable, since, for example, int may not be defined of the same size on different architectures.

[Solved] How to access structure member using address of structure , Declare variables of the struct type; Use DOT notation to access cs31 base address of the cs31 array student1.name base address of the  Structure may contain the Pointer variable as member. Pointers are used to store the address of memory location. They can be de-referenced by ‘*’ operator. s1 is structure variable which is used to access the “structure members”. Here num is any variable but it’s address is stored in the Structure member ptr ( Pointer to Integer)

CS31: Intro to C Structs and Pointers, Pointer Within Structure in C Programming : s1 is structure variable which is used to access the “structure members”. s1.ptr = # s1.name = "Pritesh". Here num is any variable but it's address is stored in the Structure member ptr (Pointer Similarly we have stored the base address of string to pointer  Accessing Element in Structure Array. Array of Structure can be accessed using dot[.] operator. Here Records of 3 Employee are Stored. ‘for loop’ is used to Enter the Record of first Employee. Similarly ‘for Loop’ is used to Display Record.

struct (C programming language), So, here name, address and phone number are those different types of data. Here For that, we need to access the roll number of the first student. We do this by to use variables in a structure. p1.roll_no can be understood as roll_no of p1​. Example program for C structure using pointer: In this program, “record1” is normal structure variable and “ptr” is pointer structure variable. As you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access data using pointer variable.

C pointer within Structure - C Programming, Data structures can be declared in C++ using the following syntax: This operator serves to access the member of an object directly from its address. Structure members can be accessed by any function, anywhere in the scope of the Structure. Functions inside Structure: C structures do not permit functions inside Structure; Static Members: C Structures cannot have static members inside their body; Access Modifiers: C Programming language do not support access modifiers. So they cannot be used

Comments
  • Search for "C struct padding alignment". (Your code is not portable btw.)
  • Note the casting and pointer arithmetic. (char*)pa + 4 is adding the size of 4 chars. (int*)pa + 2 is adding the size of 2 ints.
  • Why not use something else then the member i in your example? i as being the 1st member could very well "reliably" be accessed by doing first = *(int*)pa;
  • @alk - I just wanted to concisely show how to obtain the correct offset for any member, and how to use the offset correctly. It's also reliable to say real code will do for instance pa->j instead of mucking with offsets and casts.
  • "This also means that the code is not portable" this is not was is commonly understood as being "not portable". Did not DV, BTW.