/* usingptrs.c - demonstrates using C pointers For CS 60 assignment 2, part 1, Fall 2009: Run AS-IS and explain the output (see instructions). updated by cmc, 10/6/09 */ #include #include int main(void) { char cval, *cptr; int ival, *iptr; double dval, *dptr; /* a. Using a pointer to char */ cval = 'K'; cptr = &cval; printf("\na. %c (actually %d) @ %p\n", *cptr, cval, cptr); /* b. Using pointers to int and double */ ival = cval; iptr = &ival; dptr = &dval; /* notice how dval assigned */ *dptr = *iptr; printf("\nb. %d @ %p, and %.1f @ %p\n", ival, iptr, dval, dptr); /* c. Using sizeof operator for char, int and double values */ printf("\nc. bytes @ %p, %p and %p are %d, %d and %d\n", cptr, iptr, dptr, sizeof cval, sizeof ival, sizeof dval); /* d. Using sizeof operator for pointers */ printf("\nd. %p @ %p in %d bytes, and %p @ %p in %d bytes\n", cptr, &cptr, sizeof cptr, dptr, &dptr, sizeof dptr); /* e. Using a pointer for dynamic memory allocation and use */ iptr = malloc(sizeof(int) * 10); for (ival = 0; ival < 10; ival++) *(iptr + ival) = ival * 10; printf("\ne. value\t@\n"); for (ival = 0; ival < 10; ival++) printf("%8d\t%p\n", iptr[ival], iptr + ival); free(iptr); return 0; }