Array
-----------
Arrays
Predict the output of below program:
| #include <stdio.h> int main() { int arr[5]; // Assume that base address of arr is 2000 and size of integer // is 32 bit arr++; printf ( "%u" , arr); return 0; } |
| A |
2002 |
|
2004 |
| C |
2020 |
|
lvalue required |
Discuss it
Question 1 Explanation: Array name in C is implemented by a constant pointer. It is not possible to apply increment and decrement on constant types.
Predict the output of below program:
| #include <stdio.h> int main() { int arr[5]; // Assume base address of arr is 2000 and size of integer is 32 bit printf ( "%u %u" , arr + 1, &arr + 1); return 0; } |
|
2004 2020 |
| B |
2004 2004 |
|
2004 Garbage value |
| D |
The program fails to compile because Address-of operator cannot be used with array name |
Discuss it
Question 2 Explanation: Name of array in C gives the address(except in sizeof operator) of the first element. Adding 1 to this address gives the
address plus the sizeof typethe array has. Applying the
Address-of operator before the array name gives the address of the whole array. Adding 1 to this address gives the
address plus the sizeof whole array.
What is output?
| # include <stdio.h> void print( int arr[]) { int n = sizeof (arr)/ sizeof (arr[0]); int i; for (i = 0; i < n; i++) printf ( "%d " , arr[i]); } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; print(arr); return 0; } |
| A |
1, 2, 3, 4, 5, 6, 7, 8 |
| B |
Compiler Error |
|
1 |
| D |
Run Time Error |
Discuss it
Question 3 Explanation: See http://www.geeksforgeeks.org/using-sizof-operator-with-array-paratmeters/ for explanation.
Output of following program?
| #include<stdio.h> int main() { int a[] = {1, 2, 3, 4, 5, 6}; int *ptr = ( int *)(&a+1); printf ( "%d " , *(ptr-1) ); return 0; } |
| A |
1 |
| B |
2 |
|
6 |
| D |
Runtime Error |
Discuss it
Question 4 Explanation: &a is address of the whole array a[]. If we add 1 to &a, we get “base address of a[] + sizeof(a)”. And this value is typecasted to int *. So ptr points the memory just after 6 is stored. ptr is typecasted to "int *" and value of *(ptr-1) is printed. Since ptr points memory after 6, ptr – 1 points to 6.