Look,
typedef struct jig
{
int *a;
int *b;
}temp;
now stage 1 :
temp *b;
b= (temp*)malloc(sizeof(temp));
if(b->a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b->b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
output is :
a is null
b is null
now stage 2 :
temp b;
if(b.a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b.b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
output is :
a is not null
b is not null
why this is happening?
Hence, the default value of a pointer is always nil. Here, in the line var ptr = new(int) , the variable ptr becomes a pointer of type int .
N@G3 " [...] a variable or pointer is given a null "value" by default [...] " Pointers have no specific default value.
A pointer is a variable that points to another variable. This means that a pointer holds the memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable.
No, it will be initialized to the NULL pointer value, whether or not its representation is zero. For pointers, the constant 0 transforms to the NULL pointer value, not the bit pattern of all zeros.
Pointers have no default value. The value they have is just whatever junk was in the memory they're using now. Sometimes a specific compiler will zero out memory, but that's not standard so don't count on it.)
The memory from malloc being NULL was a coincidence; it could have been any other value just as easily. You need to and should always manually set all your pointers to NULL.
Another alternative is you can also use calloc, which does the same thing as malloc but sets all bits to 0 in the block of memory it gives you. This doesn't help with stack variables though, so you still have to set those to NULL by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With