midterm-2-ans

midterm-2-ans - CS240 Programming in C Midterm Exam 2,...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
CS240 Programming in C Midterm Exam 2, March 30, 2011 This exam is closed book, closed notes. Please do not open the exam until you are told to do so. There are 7 pages in this booklet. Please make sure that you have them all. Extra blank pages are provided in the back. Name: Section: 9:30 am - 11:20 am F F930 11:30 am - 1:20 pm F F1130 1:30 pm - 3:20 pm F F130 3:30 pm - 5:20 pm F F330 9:30 am - 11:20 am R R930 11:30 am - 1:20 pm R R1130 3:30 pm - 5:20 pm R R330 11:30 am - 1:20 pm T T1130
Background image of page 1

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

View Full DocumentRight Arrow Icon
Question 1. (12 points) Write the output of the following program. #include <stdio.h> int main() { int array[10] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; int *iptr = (int *)&array; void *vptr = &array; iptr = iptr + 8; vptr = ((char *)vptr) + 8; printf("%d\n", *iptr); printf("%d\n", *(int *)vptr); iptr = (int *) (((double *)iptr) - 2); vptr = ((int *)vptr) - 2; printf("%d\n", *iptr); printf("%d\n", *(int *)vptr); } Answer: 18 12 14 10 1
Background image of page 2
Question 2. (14 points) Consider the following definitions: struct intarray { int size; int *data; }; struct intarray * create_intarray(int size) { struct intarray *a; a = malloc(sizeof(struct intarray)); a->size = size; a->data = malloc(sizeof(int)*size); return a; } Rewrite the above function using just one call to malloc: struct intarray * create_intarray(int size) { struct intarray *a; a = ____________________; a->size = size; a->data = _______________; return a; } Answer: struct intarray * create_intarray(int size) { struct intarray *a; a = malloc(sizeof(struct intarray)+sizeof(int)*size); a->size = size; a->data = a+1; // the following also works // a->data = ((char *)a+sizeof(struct intarray)); return a; } 2
Background image of page 3

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

View Full DocumentRight Arrow Icon
Question 3. (16 points) What gets printed by the following? Write ’?’ if it would print garbage. #include <stdio.h> int h1(int c) { return c + 1; } int h2(int c) { return c - 1; } int g1(int a, int b, int(*h)(int)) { return a + h(b); } int g2(int a, int b, int(*h)(int)) { return a * h(b); } void f1(int *arg1, int *arg2, int(*g)(int, int, int(*h)(int)))
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 11

midterm-2-ans - CS240 Programming in C Midterm Exam 2,...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online