What will be the output of the following code?int main() { int *ptr = NULL; ptr = (int*)malloc(sizeof(int)); *ptr = 5; printf("%d\n", *ptr); free(ptr); return 0;}
Question
What will be the output of the following code?int main() { int ptr = NULL; ptr = (int)malloc(sizeof(int)); *ptr = 5; printf("%d\n", *ptr); free(ptr); return 0;}
Solution
The output of the code will be 5.
Here's the step by step explanation:
-
An integer pointer
ptris declared and initialized toNULL. -
Memory of size equal to an integer is allocated dynamically and the address of the allocated memory is assigned to
ptr. -
The value at the address pointed by
ptris set to 5. -
The value at the address pointed by
ptris printed, which is 5. -
The dynamically allocated memory is freed.
-
The program returns 0 indicating successful execution.
Similar Questions
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;}
What will be the output of the following C code? #include <stdio.h> void main() { int x = 0; int *ptr = &x; printf("%d\n", *ptr); }
What will be the output of the following C code?int main(){char *ptr1, *ptr2;printf("%d %d", sizeof(ptr1), sizeof(ptr2));return 0;} 4 4Undefined2 21 1
What will be the output of the following code?int main() { int a = 10; int *p = &a; *p = 20; printf("%d\n", a); return 0;}
What will be the output of the given program? int main(){void * p;p = calloc(10,sizeof(int));cout<<"The number of bytes reserved are " << 10*sizeof(int);free (p);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.