I am new to C, and while reading I came across the concept of pointers. So, after references from multiple books and sites, I still cannot figure out how a pointer is used to save memory.
A pointer points to the address location of another variable, eg: int *ptr =&var;
From the above eg, ptr holds the address of var, which by itself is stored in another memory location. So my question is:
1) why do we use pointers when the pointer value is stored in a separate memory location, thus increasing memory usage?
2) Why not we directly use the variable name(var in this case) instead of using another memory space for pointers
Pointers are not exactly used for the concept of memory saving. Even though certain circumstances saves a little memory like passing a parameter (like struct )with its address to function rather than variable itself . size of a struct may be more than 4 bytes where as pointer size is just fiur . it mainly used to ease of manipulation of data and avoid redundant steps. Learn about pass by value and pass reference you will know a bit why pointers are used. Your question why pass to pointer rather variable itself .
When you pass the variable it creates a new variable on stack which is local to that function of we need those changes to reflect back In the calling function then you have to pass the variable back and re assign. But in case of pointers it is using the original variable so there is no need of those extra step of passing variable back and restoring of same .
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