In: Electrical Engineering
5. Given the following declarations and assignments, what do these expressions evaluate to?
int a1[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int *p1, *p2;
p1 = a1+3;
p2 = &a1[2];
(a) *(a1+4) (b) a1[3] (c) *p1 (d) *(p1+5) (e) p1[-2]
(f) *(a1+2) (g) a1[6] (h) *p2 (i) *(p2+3) (j) p2[-1]
Dear Student,
The given line of statements are in C /C++ programming language.
int a1[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
This line of code states that a 1-dimensional integer array named a1 of 10 elements has been declared and initialized with numbers from 9 to 0.
Array - It is a group of elements of same data types. Example integer array can contain elements which are integers only. Index of an array gives the position of elements in that array. It starts with 0 and wriiten in third brackets [ ].
a1[0] = 9 ----- The first element
a1[1] = 8 ----- The second element and so on upto last element
a1[9] = 0 ----- The last element
Last index is always 1 less than the size of array
Last index = size of array - 1 = 10 - 1 = 9
int *p1, *p2;
This code declares two pointer variables named p1 and p2. Pointer variables are the variables that stores address of other variables and we can access the value of that variable through this pointer variable.
p1 = a1+3;
This code stores address in pointer variable p1. a1 gives the base address of array a1 i.e. address of first element a1[0]. When 3 is added to it, (a1 + 3) gives address of address of element a1[0+3] i.e. a1[3] element.
Hence p1 stores address of element a1[3].
p2 = &a1[2];
This code stores address of element a1[2] in pointer variable p2. & is used to provide the address of any variable.
a) *(a1+4) The expression (a1 + 4) gives the address of a1[0+4] = a1[4]. Now the * operator gives access to the value stores in address of a1[4]. The value of a1[4] is 5
Hence *(a1 + 4) = 5
b) a1[3] = 6
c) *p1 It gives the value store in pointer variable p1. p1 stores the address of element a1[3].
Hence *p1 = 6
d) *(p1+5) p1 stores the address of element a1[3]. So (p1 + 5) gives the address of element a1[3+5] = a1[8]. Now * operator on (p1 + 5) gives the value of a1[8].
Hence *(p1 + 5) = 1
e) p1[-2] Index of pointer variable start from 0 and goes in reverse direction. p1 stores address of element a1[3].
So p1[0] = a1[3]
p1[-1] = a1[2]
p1[-2] = a1[1]
p1[-3] = a1[0]
Hence p1[-2] = 8
f) *(a1+2) = a1[0+2] = a1[2] = 7
Hence *(a1 + 2) = 7
g) a1[6] = 3
h) *p2 p2 stores the address of a1[2]. On applying* operator in it gives the value of a1[2] i.e. 7
Hence *p2 = 7
i) *(p2+3) p2 stores address of a1[2], so (p2 + 3) gives address of a1[2+3]=a1[5]. On applying * operator it gives value of a1[5].
Hence *(p2 + 3) = 4
j) p2[-1] p2 stores address of a1[2]. Therefore
p2[0] = a1[2]
p2[-1] = a1[1]
p2[-2] = a1[0]
Hence p2[-1] = 8
Please give a positive rating to this answer. Thank you !