Some comments to complement what Salem and laserlight said:
Code:
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
struct point *next;
};
int main ()
{
// 'new' object will be allocated on stack because
// you are getting it's address later ('&new').
// No need, here, to initialize it to NULL, since malloc() will do,
// if failure occurs.
struct point *new;
// Notice sizeof has 2 syntaxes:
// 'sizeof object' or 'sizeof(type|object)'
// Since 'new' points to an object of 'struct point' type,
// 'sizeof *new' is equivalent to 'sizeof(struct point)', in this case.
new = malloc ( sizeof *new );
if ( new == NULL )
return EXIT_FAILURE;
// Just to put some values in the allocated structure.
new->x = 1;
new->next = NULL;
// OBS: You don't need to cast the pointers to 'void *'.
// printf's '%p' format specifier need to get an 'void *' argument,
// but all pointers are compatible to 'void *'.
// '&new' will result in the address of 'new', not the address of the object allocated by malloc.
printf ( "addresses of a struct pointer variable new : %p \n", &new );
// 'new' contains the address of the object, as returned by malloc.
printf ( "value of a struct pointer variable new : %p \n", new );
// The first element of the structure has the same address returned by malloc!
printf ( "addresses of a struct object x : %p \n", &new->x );
// This address is sizeof(int) bytes ahead of the address returned by malloc.
// But this can be 4 bytes ahead or 8 bytes ahead due to alignment.
// ISO 9899 6.7.2.1 § 12 states each non-bitfield members alignment is
// implementation defined. For x86-64 a pointer can be aligned by QWORD (8 bytes).
printf ( "addresses of a struct object pointer next : %p \n", &new->next );
printf ( "Data of a struct object x : %d \n", new->x );
printf ( "Data of a struct object new : %p \n", new->next );
return EXIT_SUCCESS;
}
Code:
$ cc -o test test.c
$ ./test
addresses of a struct pointer variable new : 0xffffcc28
value of a struct pointer variable new : 0x800000440
addresses of a struct object x : 0x800000440
addresses of a struct object pointer next : 0x800000448
Data of a struct object x : 1
Data of a struct object new : 0x0
Here, 0xffffcc28 points to the stack. 0x800000440 is the beginning of the memory block allocated by malloc. Notice new and &new->x are the same value. The address of new->next starts 8 bytes after the beginning of the block allocated because the compiler aligned next to a QWORD boundary, in this case, for x86-64 mode. This can be different to i386 mode or other processors.
[]s
Fred