Thursday, July 9, 2009

Help! Print offsets for elements of an array! For C Programming!?

int main(void)


{


int array[10] = { 101, 102, 103, 104, 105, 106, 107, 108, 109, 110};


int *ptr = %26amp;array[0];


int i;





printf("\nArray @ %p\n\n", ptr);





for (i = 0; i %26lt; 10; i++) {


printf( "Array[%d] @ %p = %d\n", i, %26amp;array[i], *ptr);


}


--------------------------------------...





thats what i have but when i debug it, each element in the array comes out to be 101 (instead of 101, 102...110).





I have this much, what am i doing wrong?





Also how do i print each adress's offset???





This is C, not C++

Help! Print offsets for elements of an array! For C Programming!?
You aren't incrementing your pointer...





int main(void) {


intarray[10] = { 101, 102, 103, 104, 105, 106, 107, 108, 109, 110};


int *ptr = %26amp;array[0];


int i;





printf("\nArray @ %p\n\n", ptr);





for (i = 0; i %26lt; 10; i++) {


printf( "Array[%d] @ %p = %d\n", i, %26amp;array[i], *ptr);


ptr++;


}





return 0;


}
Reply:*ptr is always going to be 101. If you want to get the offset from the beginning of the array, you could subtract ptr from the element position %26amp;array[i] and get the offset.


No comments:

Post a Comment