Unlock the Power of Pointers in C Programming
Understanding Addresses in C
When you declare a variable var in your program, the compiler allocates a specific memory location to store its value. You can access this memory address using the unary operator & followed by the variable name, like &var. This address is where the value entered by the user is stored when using the scanf() function.
Let’s Get Hands-On!
Take a look at this example:
int var;
printf("%p", &var);
Run this code, and you’ll see the memory address of var printed out. Note that the address will likely be different each time you run the program.
Pointers: The Game-Changers
Pointers are special variables that store memory addresses rather than values. They’re declared using an asterisk (*) before the pointer name, like int *p. This syntax tells the compiler that p is a pointer that can hold the memory address of an int variable.
Declaring Pointers: Multiple Ways
You can declare pointers in various ways:
int *p1, *p2;– declaring multiple pointersint *p;– declaring a single pointer
Assigning Addresses to Pointers
Let’s assign the address of a variable c to a pointer pc:
int c = 5;
int *pc = &c; // assigning address of c to pc
Now, pc holds the memory address of c.
Unleashing the Power of Pointers
To access the value stored at the memory address held by a pointer, use the dereference operator (*) like this:
int c = 5;
int *pc = &c;
printf("%d", *pc); // prints 5
Changing the Value Pointed by a Pointer
Let’s modify the value of c through the pointer pc:
int c = 5;
int *pc = &c;
*pc = 1; // changes the value of c to 1
Now, c is equal to 1.
Working Example: Pointers in Action
Here’s a complete program demonstrating pointer operations:
int main() {
int c = 22;
int *pc = &c;
printf("Value of c: %d\n", c);
printf("Address of c: %p\n", &c);
*pc = 2; // changes the value of c to 2
printf("New value of c: %d\n", c);
return 0;
}
Common Pitfalls to Avoid
When working with pointers, it’s essential to understand the syntax correctly. A common mistake is using int *p = &c; without realizing that p is the pointer, not *p. To avoid this confusion, use the syntax int *p; followed by p = &c;.
Now that you’ve grasped the basics of pointers, you’re ready to explore how they relate to arrays in the next tutorial.