I didn’t understood the working procedure for questions 6,7 and 8 like how to know what is the output of the given 3 programs
Pointers MCQ Questions
Q6 What will be the output of the following program?
#include
using namespace std;
int main() {
int arr[]={0,1,2,3,4};
int i, ptr;
for(ptr= arr, i=0; ptr+i <= arr+4; ptr++, i++) cout<<(ptr+i);
return 0;
}
A) 01234
B) 024
C) 234
D) 12340
7)Q7 In the piece of code, arr[ ][ ] is a 2D array and assume that the
contents of the 2D array are already filled up. What is stored in the
variable sum at the end of the code segment?
int arr[3][3];
int i, sum=0; i = 0; while(i<3) {
sum += * ( * (arr+i)+(i++)); }
printf(“sum:%d”, sum);
A) Sum of all elements in the matrix
B) Sum of alternate elements in the matrix
C) Sum of the elements along the principal diagonal
D) None
Q8 Would the following program compile?
#include
using namespace std;
int main() {
int a=10, *j; void *k; j=k=&a; j++;
k++; cout<<j<<k; return 0;
}Would the following program compile?
A) Yes
B) No
I didn’t understood the working procedure for the above programs
just follow the loop.
first it will print value at ptr which is 0. then they are incrementing ptr by 1 and i by 1
that means now it will print value ptr +1 + 1 ie 3rd element which is 2.
again it will incremnt by 2 and this time it will print ptr+4 ie 4th element which 4.
and loop will stop after that.
024 will be the answer.
to solve this problem u should know this->
a[i]= * (a+i)
similarly
a[i][j]= * (a[i]+j) = * ( * (a+i) + j )
so if u see this
this is nothing but arr[i][i++]
now i think u can calculate answer on ur own
correct answer will be-> Sum of the elements along the principal diagonal
because it compute sum of element at index (0,0 , 1,1 , 2,2 )
Ans is No. it wont compile…
compile error is : error: invalid conversion from ‘void*’ to ‘int*’
why?
due to line j = k = &a.
in cpp, void* is a generic pointer and it can point to any type of element.
statements like k=&a, k=j or k=j=&a are all valid…
but j = k is not valid. if you assigns a generic type(void*) to a specific one(int*), you need to cast it. i.e. int* can not point to void*(since void* is superset)
so cast it… j = (int*)k will work.