Work with an array of structs and pointer arithmetic on arrays. What output is produced by accessing c[1].courseno and (*(c + 2)).coursename in the code below?
#include
int main()
{
struct course
{
int courseno;
char coursename[25];
};
struct course c[] = { {102, "Java"},
{103, "PHP"},
{104, "DotNet"} };
printf("%d ", c[1].courseno);
printf("%s
", (*(c+2)).coursename);
return 0;
}
C Programming
Structures, Unions, Enums
Difficulty: Easy
Choose an option
-
A103 DotNet
-
B102 Java
-
C103 PHP
-
D104 DotNet
Answer
Correct Answer: 103 DotNet
Explanation
Introduction / Context: This problem checks understanding of array indexing with structs and pointer arithmetic on arrays of structs.
Given Data / Assumptions:
- c is an array with three elements: {102,"Java"}, {103,"PHP"}, {104,"DotNet"}.
- We print c[1].courseno and then (*(c+2)).coursename.
Concept / Approach: c[1] indexes the second struct in the array. c + 2 points to c[2], and *(c + 2) dereferences that element. Accessing fields then prints the stored number and string.
Step-by-Step Solution:
c[1].courseno = 103 *(c + 2) is c[2]; c[2].coursename = "DotNet" Output: "103 DotNet"Verification / Alternative check: Rewriting (*(c+2)).coursename as c[2].coursename yields the same result by array indexing equivalence.
Why Other Options Are Wrong:
- 102 Java: That would be c[0], not the requested elements.
- 103 PHP: Mixes first value from c[1] with coursename from c[1] instead of c[2].
- 104 DotNet: Would require printing c[2].courseno, not c[1].courseno.
Common Pitfalls: Off-by-one mistakes when moving between zero-based indexing and pointer arithmetic (c + n vs c[n]).
Final Answer: 103 DotNet