Knowee
Questions
Features
Study Tools

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);

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be "rld".

Here's the step by step explanation:

  1. The code declares a character array str[] and initializes it with the string "world".

  2. The printf function is used to print a string. The %s inside the printf function is a format specifier that tells the function to expect a string as an argument.

  3. str + 2 is used as the argument for the printf function. This is pointer arithmetic. In C, the name of an array is a pointer to the first element of the array. So, str is a pointer to the 'w' character in "world". When you add 2 to str, it moves the pointer two places to the right. So, str + 2 is a pointer to the 'r' character in "world".

  4. Therefore, when printf prints the string starting from str + 2, it prints "rld".

This problem has been solved

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;}

1/3

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.