
One code at a time
Do C pointers have you scratching your head, feeling like you've stumbled into a sci-fi movie? Don't worry; I'm here to make them as simple as ordering a pizza online. By the way, I'm a big fan of pizza! Let's turn those pointer puzzles into a piece of cake!" ๐๐ฐ๐
Pointers in C
A pointer is a special variable designed to store memory addresses of other variables. You can think of pointers as "signposts" because they show you where things are stored in the computer's memory, rather than holding the things themselves.
So, the basic way to declare a pointer in C is:
type *pointerName;type: The type of data the pointer will point to (likeintorchar).*: The asterisk (*) tells us it's a pointer.pointerName: You choose a name for your pointer variable.
Hey, int* p; int *p; int * p; are all valid ways to declare a pointer so don't get confused.
Normally, to get the address of a variable, & operator is used.
#include <stdio.h>
/**
* main - storing the address of variable into a pointer
*
* Return: Always 0.
*/
int main(void)
{
int n;
int *p;
n = 98;
p = &n; // To get the address of the variable n, you have to use &n
printf("Address of 'n': %p\n", &n);
printf("Value of 'p': %p\n", p);
//%p is the specifier used to print address when using printf
return (0);
}
Output
Address of 'n': 0x7ffc6f64b6d4
Value of 'p': 0x7ffc6f64b6d4
Dereferencing
Dereferencing is like looking inside a pointer to see the value it's holding. We use the
*called the dereference operator to achieve this. It's like a 'fetch' button, it helps you get the actual value stored in a pointer.For example:
int x; int *pt; x = 20; pt = &x; printf("%d", *pt); // Output: 20Here, we made
ptpoint to the address ofx. To find out what's stored at that address, we just used*pt.Note: In the above example, pc is a pointer, not
*pt. You cannot and should not do something like*pt = &x;Let's see it this way, we have a variable
nand pointerpof typeintp = &n*p = n*p != &nKeep in mind that the pointer's data type must be the same as the data type of the variable you're dealing with. The following example is incorrect:
char c; int *p; p = &c;Let's make this clearer by considering an example that works:
#include <stdio.h> /** * main - derefencing pointers * * Return: Always 0. */ int main(void) { int n; int *p; n = 98; p = &n; printf("Value of 'n': %d\n", n); printf("Address of 'n': %p\n", &n); printf("Value of 'p': %p\n", p); *p = 402; printf("Value of 'n': %d\n", n); return (0); }Output
Value of 'n': 98 Address of 'n': 0x7ffd9c1969a4 Value of 'p': 0x7ffd9c1969a4 Value of 'n': 402Takeaway, in pointers, we can consider this
&as the reference operator while*is the dereference operator. I hope this helps, didn't want to bore you with a long piece.
Breathe!
Stay curious!!
Keep coding!!!

