Knowee
Questions
Features
Study Tools

What will you see on the terminal?int main(void){ int *ptr; *ptr = 98; printf("%d\n", *ptr); return (0);}

Question

What will you see on the terminal?

int main(void) {
    int *ptr;
    *ptr = 98;
    printf("%d\n", *ptr);
    return (0);
}
🧐 Not the exact question you are looking for?Go ask a question

Solution

The code you've written is in C language and it's trying to assign a value to a pointer without initializing it first. This is undefined behavior in C.

Here's a step by step explanation:

  1. int *ptr; This line declares a pointer to an integer. However, it doesn't initialize the pointer, so it points to some arbitrary memory location.

  2. *ptr = 98; This line tries to write the value 98 to the memory location that ptr points to. Since ptr was never initialized, this is undefined behavior. The program could crash, or it could overwrite some other data in your program, or it could appear to work correctly. It's unpredictable.

  3. printf("%d\n", *ptr); This line tries to print the value at the memory location that ptr points to. Again, since ptr was never initialized, this is undefined behavior.

  4. return (0); This line returns 0 from main, indicating that the program completed successfully. However, if the program didn't crash earlier, it's purely by luck.

In conclusion, you should never write to or read from an uninitialized pointer. Always make sure your pointers are initialized to a valid memory location before you use them.

This problem has been solved

Similar Questions

What will you see on the terminal?int main(void){ int *ptr; *ptr = 98; printf("%d\n", *ptr); return (0);}It doesn’t compileSegmentation Fault980

What is the output of the following code snippet?int x = 5;int y = 10;int *ptr = &x;*ptr = y;printf("%d", x);510015Generates a compilation error

What will the following code output?#include <stdio.h>int main() {    int arr[3] = {1, 2, 3};    int *p = arr;    printf("%d\n", *(p + 2));    return 0;}

What will be the output of following program?main( ){int k, num = 30 ;k = ( num > 5 ? ( num <= 10 ? 100 : 200 ) : 500 ) ;printf ( "\n%d", num ) ;}

What will be the output of the following C code?#include <stdio.h>int main() {    int i;    for (i = 0; i < 5; i++);    printf("%d\n", i);    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.