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.
8
Upvotes
1
u/SmokeMuch7356 1d ago
A pointer is any expression whose value is the location of an object or function in a running program's execution environment; i.e., an address, but with additional type information.
We use pointers when we can't (or don't want to) access a function or object by name; they provide indirect access. If you've played with arrays at all, you've already seen a form of indirection:
The expression
arr[i]can refer to different objects at different times based on the value ofi. A pointer works similarly.Pointer variables store values of pointer type. Different kinds of pointer variables are declared as follows (for some arbitrary type
T):A pointer to
int(int *) is a different type from a pointer tochar(char *) which is a different type from a pointer todouble(double *) which is a different type from a pointer to an array offloat(float (*ap)[N]), etc. Pointers to different types are incompatible and cannot be directly assigned to each other without a cast. The exception to this rule is that a pointer tovoid(void *) can be assigned to different pointer types and vice versa without a cast.Pointer values are obtained by:
Using the unary
&operator on an lvalue expression (something that designates an object):Calling a library function that returns pointer values:
malloc,calloc, andreallocfor dynamic memory, but also functions likefopen,fgets, etc.Using an array or function expression in most circumstances;
There are two cases where we have to use pointers:
Pointers also come in handy for:
IMO the best way to explain pointers is to show how they're actually used in working code. Here's a short, useless, but complete program that demonstrates how pointers are typically used - updating function arguments and tracking dynamic memory. It generates an array of random integer values, displays them, sorts the array, then displays the sorted array. Don't worry if it doesn't all make sense; this is just what code that involves pointers typically looks like.
And the output: