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);
}
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:
-
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. -
*ptr = 98;
This line tries to write the value98
to the memory location thatptr
points to. Sinceptr
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. -
printf("%d\n", *ptr);
This line tries to print the value at the memory location thatptr
points to. Again, sinceptr
was never initialized, this is undefined behavior. -
return (0);
This line returns0
frommain
, 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.
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;}
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.