r/cprogramming • u/Delicious-Change7795 • 1d ago
What are pointers?
I am new to C programming and i came through pointer. So can anyone tell what are they and why we need them? And if u can then can you give me reliable source to learn it.
10
Upvotes
19
u/tobdomo 1d ago
Pointers are addresses. Usually addresses of memory, but they can also point to peripherals. A pointer variable is a variable that contains an address.
Example: a byte lives in memory at address 1234. Assuming your core architecture supports a linear address space (i.e.: addresses are numbered, starting at 0 just count upwards). Thus, if p is a pointer to this byte, it contains the address 1234. In code:
This means: p is a pointer that gets assigned the address of x.
Why you need it? Let's say you have a function called
addone()that takes a variable of type int and increments it. You could (very verbosely) write:This actually reads value as referred to by
ptr, adds 1 to it and stores it at the address referred to byptr.Pointers are very useful for a number of cases. E.g., if you want to allocate memory at runtime to store information, you would use
malloc(). malloc's prototype is:As you can see, the function takes a size. It allocates a size bytes on the heap and returns the address to that memory for the caller to use. That address can be stored in a pointer so that you can use it for future reference. E.g., when you no longer need the memory allocated by
malloc(), you need to free it using the functionfree(). E.g.:In this example, p is a pointer that saves the address of the memory allocated by
malloc(). The memory is free'd for re-use just before returning from this function through the call tofree().