What is the output of the following code?char str[] = "world";printf("%s\n", str + 2);
Question
What is the output of the following code?char str[] = "world";printf("%s\n", str + 2);
Solution
The output of the code will be "rld".
Here's the step by step explanation:
-
The code declares a character array
str[]and initializes it with the string "world". -
The
printffunction is used to print a string. The%sinside theprintffunction is a format specifier that tells the function to expect a string as an argument. -
str + 2is used as the argument for theprintffunction. This is pointer arithmetic. In C, the name of an array is a pointer to the first element of the array. So,stris a pointer to the 'w' character in "world". When you add 2 tostr, it moves the pointer two places to the right. So,str + 2is a pointer to the 'r' character in "world". -
Therefore, when
printfprints the string starting fromstr + 2, it prints "rld".
Similar Questions
What is the output of the following code?char str[] = "hello";int len = strlen(str);printf("%d\n", len);
What is the output of the following code?char str1[] = "C programming";char str2[20];strcpy(str2, str1);printf("%s\n", str2);
What does the following code print?#include <stdio.h>int main() { char str[] = "Hello, World!"; char *ptr = str + 7; printf("%s\n", ptr); return 0;}
What will be the output of the following code?#include <stdio.h>int main() { char str[] = "ABCDE"; printf("%c\n", str[2] + 3); return 0;}
What will be the output of the following code?#include <stdio.h>int main() { char str[] = "Hello"; str[0] = 'M'; printf("%s\n", str); return 0;}
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.