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 value98to the memory location thatptrpoints to. Sinceptrwas 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 thatptrpoints to. Again, sinceptrwas never initialized, this is undefined behavior. -
return (0);This line returns0frommain, 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 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 code snippet?123456789#include <stdio.h>int main() { int a = 7, b = 11; int *ptr = &a; int x = *ptr * *ptr + b; printf("%d", x); return 0;}
What will be the output of the given code?123456789101112#include <stdio.h> void fun(int *ptr){ *ptr = 30;}int main(){ int y = 20; fun(&y); printf("%d", y); return 0;}
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;}
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.