+ 1
Why mostly in c program using pointer pointer is daclared in this way ? *ptr = NULL
#include <stdio.h> int main() { int a[5] = {22, 33, 44, 55, 66}; int *ptr = NULL; int i; ptr = a; for (i = 0; i < 5; i++) { printf("%d ", *(ptr + i)); } }
4 Respuestas
+ 6
Every variable in C, if you don't initialize it, comes with an arbitrary value, which basically is just the bit pattern that still remains there from former use of that point in memory.
So a pointer will have stored a random address, pointing somewhere in memory.
You don't want to risk accessing stuff randomly by accident, so you first point into nothingness.
Basically like you wouldn't point with a gun at people, even if it's not loaded.
+ 1
Is the code in SoloLearn? if it is, then share the code link. Otherwise show a copy of it. Without a code for review it's hard to tell whether the way the code is written in such way was reasonable.
(Edit)
Code posted.
0
In C language, there is no concept of auto initialization as in java. So if you do not initialize the pointer thn it will pointing to some junk location, (unknown memory address).
But if that junk location is already the address of any existing data, thn it will cause of program crash or hang the window.
So for safety purpose you should always initialize pointer to NULL
0
The rule is simple. All variables must be initialized before being used. C doesn't do it for you and the allocated space may be dirty with unexpected data. C wants to be fast. Why allocate space for a variable, write a default value inside it and then write another one chosen by the programmer? Although modern Cs tend to set defined variables to 0.
In the case of pointers put them to NULL because
if (!ptr) // do a nice malloc :)
In your case then it is useless to write
int * ptr = NULL;
If the intention is to initialize ptr with a, write directly
int * ptr = a;