Answers/Solutions to Exercises in Chapter 6, Exercise 5

E5: What will be the output of the following program?

int main()
{
	int i, a[3] = {0,1,2};

	doit(a,&a[1]);
	for(i = 0; i < 3; i++)
	  printf("a[%d]=%d\n",i,a[i]);
	return 0;
}

void doit(int *a, int* b) 
{
	a[0] = b[0];
	a[1] = b[1];
}

A5:  The actual output is below. The explanation: we start with array a with values 0, 1, 2. doit() is passed two pointers, the first points to a[0] (that contains 0) and the second points to a[1] (that contains 1). Thus the local a is like the global a, while the local b is the global a starting from the second item. Thus a[0] is set to a[1] (hence to 1), and a[1] is set to a[2] (hence to 2), and a[3] remains as it was (hence 2).

a[0]=1
a[1]=2
a[2]=2

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 6 Index