padding in structs.. 
Author Message
 padding in structs..

Hello,
just curious, and I would appreciate your comments:

In the following code I am trying to use the padding bytes in a
struct. -Not that I think this could be of any practical use, I am
just curious if the code violates anything the standard says.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>

int main(void)
{
    unsigned char tc = 0x3e;
    int i;
    unsigned char *cp;

    struct test_t
    {
        char c[10];
        double d;
    } *testStruct;
    testStruct = calloc(sizeof testStruct, 1);

    if(testStruct != NULL)
    {
        cp = (unsigned char *)testStruct;
        for (i = 0; i < sizeof *testStruct; i++)
        {
            cp[i] = tc;
            putchar(cp[i]);
        }
        putchar('\n');
/* I have set the whole struct to an unsigned char value, but don't
access a member yet */

        testStruct->d = 1.23456;
        printf("%f\n", testStruct->d);

/* now I have assigned a value to a member, and I start to fiddle
with the padding*/
        for(i = 10; i < offsetof(struct test_t, d); i++)
        {
            putchar(cp[i]);
            cp[i] = 0x41;
            putchar(cp[i]);
        }
        putchar('\n');

/* I believe it is guaranteed, that testStruct->d is still valid */
        printf("%f\n", testStruct->d);
        return EXIT_SUCCESS;
    }
    return EXIT_FAILURE;

Quote:
}

TIA, HAND

--
Robert Stankowic

"The regular early morning yell of horror" - Douglas Adams



Tue, 12 Aug 2003 02:21:54 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Padding in structs

2. padding a struct to a defined size

3. padding in structs

4. padding in a statically initialized struct

5. struct padding and sizeof

6. sizeof(struct) and padding

7. Q: howto prevent struct padding

8. create a padded struct?

9. C++ 5.0 and sizeof (struct) / padding ?

10. preventing struct padding

11. Padding to mulitple-of-8-bytes: too much padding added

12. ? pad spare ?

 

 
Powered by phpBB® Forum Software