What is the output of the following code?12345678910111213#include <stdio.h>#include <stdlib.h> int main() { int *arr = (int *)malloc(3 * sizeof(int)); arr[0] = 10; arr[1] = 20; arr[2] = 30; int *ptr = arr + 2; printf("%d", arr[2]); free(arr); return 0;}
Question
What is the output of the following code?12345678910111213#include <stdio.h>#include <stdlib.h> int main() { int *arr = (int *)malloc(3 * sizeof(int)); arr[0] = 10; arr[1] = 20; arr[2] = 30; int *ptr = arr + 2; printf("%d", arr[2]); free(arr); return 0;}
Solution
The output of the code will be "30".
Here's the step by step explanation:
-
The code starts with including the necessary libraries, stdio for standard input/output functions and stdlib for functions involving memory allocation, random number generation, etc.
-
The main function is declared, which is the entry point of the program.
-
An integer pointer 'arr' is declared and memory for 3 integers is allocated using malloc function. This memory is dynamically allocated on the heap.
-
The first, second and third elements of the array 'arr' are assigned the values 10, 20 and 30 respectively.
-
Another integer pointer 'ptr' is declared and it is assigned the address of the third element of the array 'arr'.
-
The printf function is used to print the value of the third element of the array 'arr', which is 30.
-
The dynamically allocated memory is freed using the free function to prevent memory leaks.
-
The program returns 0 indicating successful termination.
Similar Questions
What is the output for the following code?
What will be the output of the following program?1234567891011121314151617181920#include <stdio.h>void one();void two();void one() { for(int i = 0; i < 2; i++){ two(); }}void two() { printf("TWO ");}int main(){ one(); two(); return 0;}
What is the output for the following code?12345678910111213#include <stdio.h> int main() { int i = 1; while (i <= 10) { if (i % 5 == 0) { i++; continue; } printf("%d ", i); i++; } return 0; }
What is the output of the following snippet code? float n = 123.1112F; printf("%.2f", n);A. 123.11B. 123.12C. 123.13D. 123.10
What will be the output of the following code snippet?123456789101112131415#include <stdio.h> int main() { char direction = 'N'; if (direction == 'N') printf("North"); else if (direction == 'S') printf("South"); else if (direction == 'E') printf("East"); else if (direction == 'W') printf("West"); else printf("Unknown"); 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.