Thread: Structure padding

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    347

    Structure padding

    Hi,

    If i write a program like this
    Code:
    #include <stdio.h>
    int main(void)
    {
       struct test
       {
         int value1;
         int value2;
       }test1={12,23};
        
       int *p;
       p = (int *)(&test1);
       printf("%d\n",*p);
       p++;
       printf("%d\n",*p);
       return 0;
    }
    Is it correct to access the individual values using p pointer? If structure padding comes into picture will i get invalid values?

  2. #2
    Registered User
    Join Date
    May 2013
    Posts
    228
    Quote Originally Posted by Satya View Post
    Is it correct to access the individual values using p pointer? If structure padding comes into picture will i get invalid values?
    Yes, compiler padding and alignment might cause undesired and unexpected results, if you try to access members this way, not to mention that this can easily lead to an error prone code - even if anything goes as expected.
    But why would you want to do that anyway?

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    347
    Thank you for the reply. I have seen the above type of coding in this forum so wanted to clarify.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structure padding
    By MOS-6581 in forum C Programming
    Replies: 27
    Last Post: 05-21-2014, 06:37 AM
  2. C Structure Padding
    By audinue in forum C Programming
    Replies: 20
    Last Post: 07-12-2011, 10:14 PM
  3. Structure padding
    By ShashiKantSuman in forum C Programming
    Replies: 4
    Last Post: 05-03-2011, 07:50 AM
  4. Structure padding
    By MK27 in forum C Programming
    Replies: 4
    Last Post: 12-15-2009, 02:25 PM
  5. Padding in Structure
    By ganesh bala in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 09:25 PM