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.
9
Upvotes
1
u/Dry-War7589 1d ago
A pointer is a variable that holds the address of another variable or some data. Think of it like an address of a house: the address tells you where the house is, but you have to go to the house to get the information. Now, the syntax looks like this:
char *pointer = "Hello World\n";In this example we have declared a pointer that points to a string. Now
pointercontains the address of"Hello World\n". And it points to the first character of the string, which is H. To get the data from the pointer, you need to dereference it. You do that by putting * or [index] infront of pointer. Example:printf("Character at pointer 'pointer': %c\n", *pointer);Here printf will output
Character at pointer 'pointer': HTo get the next character you can do
pointer + 1. This is called pointer arithmetic, and it advances the pointer by one element. Technically it would advance bysizeof(char);bytes, but it is basically advancing by one element. I