What is a pointer and how do you declare and initialize one?
A pointer is a variable that stores the memory address of another variable.
Declaration: type *ptr; declares a pointer to a value of type.
Initialization: Use the address-of operator & to get the address of a variable: int *p = &x;.
Key concepts:
*ptr(dereference): access the value at the address stored in ptr.&var(address-of): get the address of a variable.- An uninitialized pointer contains a garbage address -- using it is UB.
- Always initialize pointers: to a valid address or to NULL.
int x = 42;
int *p = &x; // p stores the address of x
*p = 100; // changes x to 100 (dereference + assign)
printf("%d", x); // prints 100
&x -> address of x
*p -> value at address stored in p
p -> the address itself
#include <stdio.h>
int main(void) {
int x = 42;
int *p = &x; /* p points to x */
printf("x = %d\n", x); /* 42 */
printf("&x = %p\n", (void *)&x); /* address of x */
printf("p = %p\n", (void *)p); /* same address */
printf("*p = %d\n", *p); /* 42 (value at p) */
/* Modify x through pointer */
*p = 100;
printf("x after *p=100: %d\n", x); /* 100 */
/* Pointer to different types */
double d = 3.14;
double *dp = &d;
printf("*dp = %f\n", *dp); /* 3.14 */
/* Initialize to NULL if no target yet */
int *safe = NULL;
if (safe != NULL) {
printf("%d\n", *safe);
} else {
printf("safe is NULL\n");
}
return 0;
}
- •A pointer stores an address; * dereferences it to access the value
- •& gets the address of a variable
- •Always initialize pointers to a valid address or NULL
- •The type of the pointer determines how *p interprets the memory
- •Pointer to int can only safely point to int (strict aliasing rule)
- •int *p, q; declares p as pointer and q as int, NOT two pointers
- •Dereferencing an uninitialized or NULL pointer is undefined behavior
- •Pointer type must match the pointed-to type (int* for int, double* for double)
- •* in declaration means 'pointer to'; * in expression means 'dereference'