pointer_arithmetic

# pointer_arithmetic - printf"%hd\n"(p 3 Output...

This preview shows pages 1–2. Sign up to view the full content.

Pointer arithmetic exercise Consider the following program. Write the output after each printf statement inside the accompanying comment. You don’t need to write newline characters. sizeof(short) is 2, and the memory address of a[0] is 0xbf9eb8c6 . The address increases from a[0] to a[4] . The conversion speciﬁcation %p is for printing address in hexadecimal form. The conversion speciﬁcation %hd is for printing a short variable. /* pointer arithmetic */ #include <stdio.h> int main() { short *p; short a[] = {0, 1, 2, 3, 4}; short *pa[] = {a+4, a+3, a+2, a+1, a}; printf("%p\n", &a[0]); /* Output: 0xbf9eb8c6 */ printf("%p\n", &a[1]); /* Output: ___________ */ printf("\n"); printf("%d\n", a - &a[0]); /* Output: ___ */ printf("%p\n", a + 2); /* Output: ___________ */ printf("%hd\n", *(a + 4)); /* Output: ___ */ printf("\n"); p = a; printf("%p\n", ++p); /* Output: ___________ */ printf("%hd\n", p[0]); /* Output: ___ */

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: printf("%hd\n", *(p + 3)); /* Output: ___ */ printf("\n"); p = &a[4]; printf("%hd\n", *(p - 4)); /* Output: ___ */ printf("%hd\n", p[-1]); /* Output: ___ */ 1 printf("\n"); p = a + 2; printf("%hd\n", *p++); /* Output: ___ */ printf("%hd\n", *--p); /* Output: ___ */ printf("\n"); p = a + *(a + 3); printf("%d\n", a - p); /* Output: ___ */ printf("%d\n", a == &p[-3]); /* Output: ___ */ printf("\n"); p = pa[3]; printf("%hd\n", a[p - a]); /* Output: ___ */ printf("%hd\n", *(p + (a[4]-a[1]))); /* Output: ___ */ printf("\n"); printf("%d\n", pa[0] - a); /* Output: ___ */ printf("%hd\n", *(pa[4] + a[4])); /* Output: ___ */ printf("%d\n", (pa[2] - &a[2])); /* Output: ___ */ printf("\n"); { int i; for (i = 0; i < 5; i++) { *pa[i] = a[i]; printf("%hd ", a[i]); /* Output: ___________*/ } printf("\n"); } return 0; } 2...
View Full Document

{[ snackBarMessage ]}

### Page1 / 2

pointer_arithmetic - printf"%hd\n"(p 3 Output...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online