What will be the output of the following code?#include <stdio.h>int main() { char str[] = "GPT-3"; char *p = str; printf("%s\n", p + 4); return 0;}
Question
What will be the output of the following code?#include <stdio.h>int main() { char str[] = "GPT-3"; char *p = str; printf("%s\n", p + 4); return 0;}
Solution
The output of the code will be "-3".
Here's the step by step explanation:
-
The code declares a character array
str[]and initializes it with the string "GPT-3". -
A pointer
pis declared and it is pointed to the base address of the string "GPT-3". -
printf("%s\n", p + 4);is used to print the string starting from the addressp + 4. -
In C, string is an array of characters. The base address
ppoints to the first character of the string, which is 'G'. -
When we do
p + 4, it moves the pointer 4 places to the right. So, it now points to the character '-'. -
Hence, when we print the string starting from
p + 4, it prints "-3". -
The program then returns 0, indicating successful execution.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.