Warum funktioniert malloc (sizeof (pointer))?
Dieser folgende Code funktioniert einwandfrei:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node{
int a, b, c, d, e;
};
struct node *ptr = NULL;
printf("Size of pointer ptr is %lu bytes\n",sizeof (ptr));
printf("Size of struct node is %lu bytes\n",sizeof (struct node));
ptr = (struct node*)malloc(sizeof (ptr)); //Line 1
// ptr = (struct node*)malloc(sizeof (struct node)); //Line 2
ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;
printf("a: %d, b: %d, c: %d, d: %d, e: %d\n",
ptr->a,ptr->b,ptr->c,ptr->d,ptr->e);
return 0;
}
Wenn eingehalten als:
gcc -Wall file.c
Meine Frage ist: Warum ist das in Ordnung?
malloc
weist die Anzahl der Bytes zu, die in seinem Argument angegeben sind. Hiersizeof ptr
ist 8 Bytes auf meinem 64-Bit-Linux-Rechner. ich dachtemalloc
liefert 8 Bytes, aber wie greift es dann auf alle Variablen a, b, c, d, e zu? Geht es nur mit gcc oder fehlt mir etwas mit Standard C?
Soweit ich weiß, sollte "Linie 2" anstelle von "Linie 1" vorhanden sein, aber beide Linien funktionieren einwandfrei. Warum?