C
Beginner
1 min read
Pointer Basics: &, *, and Null
Example
#include <stdio.h>
#include <stddef.h> /* NULL */
int main(void)
{
int value = 42;
int *ptr = &value; /* ptr holds the address of value */
printf("value = %d\n", value);
printf("&value = %p\n", (void *)&value);
printf("ptr = %p\n", (void *)ptr); /* same address */
printf("*ptr = %d\n", *ptr); /* 42 */
/* Modifying through a pointer */
*ptr = 100;
printf("value after *ptr=100: %d\n", value); /* 100 */
/* Pointer to pointer */
int **pptr = &ptr;
printf("**pptr = %d\n", **pptr); /* 100 */
/* Null pointer check */
int *p = NULL;
if (p == NULL) {
printf("p is NULL — safe, not dereferencing\n");
}
/* sizeof a pointer (platform-dependent) */
printf("sizeof(int *) = %zu bytes\n", sizeof(int *));
/* Pointer comparison */
int arr[5] = {1, 2, 3, 4, 5};
int *start = arr;
int *end = arr + 5;
printf("Elements via comparison: ");
for (int *q = start; q < end; q++)
printf("%d ", *q);
printf("\n");
return 0;
}