Gibt es irgendwelche Garantien für C struct order?

Ich habe Strukturen ausgiebig benutzt und vor allem einige interessante Dinge gesehen*value anstattvalue->first_value wobei value ein Zeiger auf struct ist,first_value ist das allererste Mitglied, ist*value sicher?

Beachten Sie auch, dass Größen aufgrund der Ausrichtung nicht garantiert werden können. Worauf basiert der Alginment-Wert, die Größe der Architektur / des Registers?

Wir richten Daten / Code für eine schnellere Ausführung aus. Können wir dem Compiler mitteilen, dies nicht zu tun? Vielleicht können wir also bestimmte Dinge über Strukturen garantieren, wie z. B. ihre Größe?

Ich gehe davon aus, dass Sie Zeigerarithmetik für Strukturelemente ausführen, um den Elementoffset zu ermitteln- wenn wenig endian+ für big endian, oder kommt es nur auf den compiler an?

was ordnet malloc (0) wirklich zu?

Der folgende Code ist für Bildungs- / Entdeckungszwecke gedacht und soll keine Produktionsqualität haben.

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

int main()
{
    printf("sizeof(struct {}) == %lu;\n", sizeof(struct {}));
    printf("sizeof(struct {int a}) == %lu;\n", sizeof(struct {int a;}));
    printf("sizeof(struct {int a; double b;}) == %lu;\n", sizeof(struct {int a; double b;}));
    printf("sizeof(struct {char c; double a; double b;}) == %lu;\n", sizeof(struct {char c; double a; double b;}));

    printf("malloc(0)) returns %p\n", malloc(0));
    printf("malloc(sizeof(struct {})) returns %p\n", malloc(sizeof(struct {})));

    struct {int a; double b;} *test = malloc(sizeof(struct {int a; double b;}));
    test->a = 10;
    test->b = 12.2;
    printf("test->a == %i, *test == %i \n", test->a, *(int *)test);
    printf("test->b == %f, offset of b is %i, *(test - offset_of_b) == %f\n",
        test->b, (int)((void *)test - (void *)&test->b),
        *(double *)((void *)test - ((void *)test - (void *)&test->b))); // find the offset of b, add it to the base,$

    free(test);
    return 0;
}

Berufunggcc test.c gefolgt von./a.out Ich bekomme das:

sizeof(struct {}) == 0;
sizeof(struct {int a}) == 4;
sizeof(struct {int a; double b;}) == 16;
sizeof(struct {char c; double a; double b;}) == 24;
malloc(0)) returns 0x100100080
malloc(sizeof(struct {})) returns 0x100100090
test->a == 10, *test == 10 
test->b == 12.200000, offset of b is -8, *(test - offset_of_b) == 12.200000

Aktualisieren Das ist meine Maschine:

gcc --version

i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

uname -a

Darwin MacBookPro 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

Antworten auf die Frage(5)

Ihre Antwort auf die Frage