Knowee
Questions
Features
Study Tools

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

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

Solution

The output of the code will be 5.

Here's the step by step explanation:

  1. An integer pointer ptr is declared and initialized to NULL.

  2. Memory of size equal to an integer is allocated dynamically and the address of the allocated memory is assigned to ptr.

  3. The value at the address pointed by ptr is set to 5.

  4. The value at the address pointed by ptr is printed, which is 5.

  5. The dynamically allocated memory is freed.

  6. The program returns 0 indicating successful execution.

This problem has been solved

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

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.