#Day6 'C' coding challenge

#Day6 'C' coding challenge

 What is the output of the below program?

#include<stdio.h> void main() { int *ptr; printf("%u\n",ptr); printf("%d",*ptr); }

----------------------

The above program tests the following scenario:

1. How a pointer can be declared?
2. What if the pointer is not pointing to any variable?
3. What if the pointer is not pointing to any variable and we try to print the address and value pointed by the pointer?

----------------------

The pointer which is not initialized does not point to anything valuable or can point to a random memory address by chance. Our scenario in the program is an uninitialized pointer and we are trying to point the value and address to which it is pointing to. The output is always random value or we can call it garbage as it is not the intended address we are pointing it to.

---------------

The correct program for this could be

#include<stdio.h>
void main()
{
int *ptr;
int k =20;
printf("%u\n",ptr);
printf("%d",*ptr);
}

Here, ptr prints the address where k variable is stored and *ptr prints 20.

---------------

One of the declarations that can be used to avoid misuse of pointer is to assign it to NULL.

int *ptr = NULL;

Whatever the declaration, it is always important to check pointer values by adding conditions in your programs before executing anything. 

Post a Comment

0 Comments