dimanche 19 avril 2015

Inconstant difference in address of Struct when adding

I'm working on a memory where I use this header in allocated blocks. I was trying out pointer arithmetic to return new regions. Here's a simple question. When I add 1,2,3 to an address of integer, the compiler brings the next first,second,third integer's address, and they all vary by sizeof(int). But in this code a struct is of size 8. And the address vary alternatively by 2 and 8. Heres a code, with the output i get:



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

typedef struct header {
int size;
int magic;
}header;

int main() {

int n = 10;
printf("size of int %d\n", sizeof(n));
printf("addr %p\n", &n);
printf("addr+1 %p\n", &n+1);
printf("addr+2 %p\n", &n+2);
printf("addr+3 %p\n", &n+3);

header *h = malloc(sizeof(header));
printf("size of header %d\n", sizeof(header));
printf("addr %p\n", h);
printf("addr+1 %p\n", h+1);
printf("addr+2 %p\n", h+2);
printf("addr+3 %p\n", h+3);


return 0;
}


OUTPUT



size of int 4
addr 0xbfeb7898
addr+1 0xbfeb789c
addr+2 0xbfeb78a0
addr+3 0xbfeb78a4

size of header 8
addr 0x8706008
addr+1 0x8706010
addr+2 0x8706018
addr+3 0x8706020

Aucun commentaire:

Enregistrer un commentaire