Consider the following C program segment.
# include <stdio.h>
int main()
{
char s1[7] = "1234", *p;
p = s1 + 2;
*p = '0';
printf("%s", s1);
}
What will be printed by the program?
View worked solution
Answer: C
Let's trace the execution of the program step-by-step:
- Array Initialization: The statement
char s1[7] = "1234";initializes the character arrays1of size 7. The elements are stored as:s1 = {'1', '2', '3', '4', '\0', '\0', '\0'} - Pointer Assignment: The statement
p = s1 + 2;sets the pointerpto point to the element at index 2 (which iss1[2], initially containing the character'3'). - Modification: The statement
*p = '0';overwrites the character at index 2 with'0'. The arrays1now becomes:s1 = {'1', '2', '0', '4', '\0', '\0', '\0'} - Output: The
printf("%s", s1);statement prints the character sequence starting froms1[0]up to the null terminator ('\0'). Therefore, it prints 1204.
Free practice · Your answers on this page are not saved.
