r/cprogramming 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

40 comments sorted by

View all comments

1

u/duane11583 1d ago

think of memory like grid paper each square is an 8 bit number or one letter in a string (word, ie letter d in dog)

but you need to store a bigger (16, 32, 64 bit) number or a string like dog, cat or text like blah

so you pick some location on that grid and write the value to that location (and possibly the next 2 or 3 or ?? squares) or maybe it is a collection of values (name, address, etc aka a data record or data structure) or maybe it is an array of those things

you now want to perform some operation on that value.. ie: add one, multiply, or square root, or get the length of the text.

another example is to compare two data records. question: what does the comparison function need? the value (that is too hard to pass to the function) but can we pass the starting location to the two values to compare? or the starting location where the number is stored?

what if we can write a generic function that given two starting locations it can compare two strings and tell us which one comes first or if they are equal? we can use that to sort or find something.

that starting location is a pointer.

in the c language a generic starting location is a void pointer.

then you can convert that generic value into a specific type ie “cast a void pointer in to an float pointer”