What is printed by the following program?
#include<stdio.h>
int main(int argc, char *argv[])
{
int x = 1, z[2] = {10, 11};
int *p = NULL;
p = &x;
*p = 10;
p = &z[1];
*(&z[0] + 1) += 3;
printf(“%d, %d, %d\n”, x, z[0], z[1]);
return 0;
}View worked solution
Answer: D
Let's trace the execution of the program step-by-step:
-
Initialization:
int x = 1, z[2] = {10, 11};xis initialized to .- Array
zis initialized withz[0] = 10andz[1] = 11.
-
Pointer Assignment and Modification:
p = &x; *p = 10;- Pointer
pis set to the address ofx. - Dereferencing
pand assigning updates the value ofxto .
- Pointer
-
Pointer Redirection:
p = &z[1];- Pointer
pnow points toz[1]. Note thatpis not used after this statement.
- Pointer
-
Pointer Arithmetic and Modification:
*(&z[0] + 1) += 3;&z[0]is the address of the first element of the arrayz.- Adding to this pointer (
&z[0] + 1) shifts it to point to the next element, which is&z[1]. - Dereferencing this expression gives
z[1]. - Thus, the statement is equivalent to:
-
Printing the Values:
printf("%d, %d, %d\n", x, z[0], z[1]);- The printed values are:
x = 10,z[0] = 10, andz[1] = 14.
- The printed values are:
Therefore, the output printed is 10, 10, 14, which corresponds to Option D.
Free practice · Your answers on this page are not saved.
