Assume the following C variable declaration:
int *A[10], B[10][10];
Of the following expressions:
which will not give compile-time errors if used as left hand sides of assignment statements in a C program?
View worked solution
Answer: A
To determine which expressions can be used on the left-hand side (LHS) of an assignment statement without causing a compile-time error, we need to check if they evaluate to modifiable lvalues.
Given the declarations:
int *A[10], B[10][10];
Ais an array of 10 pointers toint(type:int *[10]).Bis a 2D array of integers (type:int[10][10]).
Analyzing the Expressions:
-
Expression I:
A[2]A[2]` represents the $3^{\text{rd}}$ element of the arrayA.- Its type is
int *(pointer to integer). - Since it is a pointer variable stored in an array, it is a modifiable lvalue. We can assign an address to it (e.g.,
A[2] = &x;). - No compile-time error.
-
Expression II:
A[2][3]- This is equivalent to
*(A[2] + 3). - Since
A[2]is of typeint *, dereferencingA[2] + 3yields anint. - An integer variable is a modifiable lvalue. We can assign an integer value to it (e.g.,
A[2][3] = 5;). - No compile-time error.
- This is equivalent to
-
Expression III:
B[1]B[1]represents the row of the 2D arrayB.- Its type is
int[10](an array of 10 integers). - In C, an array name or sub-array expression acts as a constant pointer to its first element and is not a modifiable lvalue. We cannot assign to an entire array directly (e.g.,
B[1] = ptr;is invalid). - Causes a compile-time error.
-
Expression IV:
B[2][3]- This represents a specific element in the 2D array
B. - Its type is
int. - An individual array element of a primitive type is a modifiable lvalue. We can assign an integer value to it (e.g.,
B[2][3] = 10;). - No compile-time error.
- This represents a specific element in the 2D array
Thus, expressions I, II, and IV will not produce compile-time errors when used on the LHS of an assignment.
Free practice · Your answers on this page are not saved.
