Clemson University -- CPSC 231 -- Fall 2009 Relationship between pointers in C and SPARC code pointers in C are addresses int a; int *pa = &a; => initialization generates ... | | add %fp, -24, %g1 a: | | <- fp-24 st %g1, [%fp-20] pa: | &a | <- fp-20 | | ... pointers in C are typed int a int char *pb; pb = &a; => gcc says "warning: assignment from incompatible pointer type" pb = (char *) &a; => explicit casting yields no compiler complaints note: the casting generates no extra work in the program ... | | add %fp, -24, %g1 a: | | <- fp-24 st %g1, [%fp-20] pb: | &a | <- fp-20 | | ... pointers and addresses in SPARC v7 are 32 bits in length int main(){ int *pa; char *pb; printf("sizeof(int) = %d\n",sizeof(int)); printf("sizeof(pa) = %d\n",sizeof(pa)); printf("sizeof(char) = %d\n",sizeof(char)); printf("sizeof(pb) = %d\n",sizeof(pb)); return 0; } will print sizeof(int) = 4 sizeof(pa) = 4 sizeof(char) = 1 sizeof(pb) = 4 address arithmetic is scaled according to the data type int main(){ int a[5]; int *pa; pa = a; printf("pa = 0x%08x\n",pa); pa++; printf("pa = 0x%08x\n",pa); pa = a+4; printf("pa = 0x%08x\n",pa); return 0; } will print pa = 0x08046de0 pa = 0x08046de4 pa = 0x08046df0 so the address "a+4" is 16 bytes offset from the base address "a" rather than just 4 bytes int main(){ char b[5]; char *pb; pb = b; printf("pb = 0x%08x\n",pb); pb++; printf("pb = 0x%08x\n",pb); pb = b+4; printf("pb = 0x%08x\n",pb); return 0; } will print pb = 0x08046df0 pb = 0x08046df1 pb = 0x08046df4 load/store of a pointer is always one word wide (4 bytes), while load/store of an object is based on the object's width ... |//////| int main(){ +----+-+ char b; |////| | b: <- fp-21 (byte) char *pb = &b; +----+-+ *pb = 0x30; pb: | &b | <- fp-20 to fp-17 (word) return 0; +------+ } |//////| ... main: save %sp, -120, %sp add %fp, -21, %g1 // construct address fp-21 st %g1, [%fp-20] // store address fp-21 into pointer pb ld [%fp-20], %g2 // load pointer for dereference mov 48, %g1 stb %g1, [%g2] // store byte into char b at address fp-21 mov 0, %i0 ret restore Summary C data type char short int int size of data type 1 2 4 load inst. to use ldb ldh ld store inst. to use stb sth st pointer data type char * short int * int * size of pointer 4 4 4 pointer increment 1 2 4 incr. inst. to use inc add _,2,_ add _,4,_ note: for unsigned char, use ldub and stub for unsigned short int, use lduh and stuh