Pointers in C - Subtopics Explained

1. Basics of Pointers

A pointer is a variable that stores the memory address of another variable. The & operator is used to get the address, and * is used to dereference the address.

int a = 10;
int *p = &a;
printf("%d", *p);  // Outputs: 10

2. Pointer and Variables

Pointers can point to any data type: int, char, float, etc. They allow indirect manipulation of variable values.

float pi = 3.14;
float *ptr = π
*ptr = 3.14159;

3. Pointer Arithmetic

You can increment/decrement pointers to move across memory addresses. This is mainly useful in arrays.

int arr[] = {1, 2, 3};
int *p = arr;

printf("%d", *(p + 1)); // Outputs: 2

4. Pointers and Arrays

Array names work like pointers. You can access array elements using pointer arithmetic.

int arr[3] = {10, 20, 30};
int *ptr = arr;

for(int i = 0; i < 3; i++) {
  printf("%d ", *(ptr + i));
}

5. Pointers and Functions

Pointers allow functions to modify variables passed as arguments (pass by reference).

void update(int *x) {
  *x = 100;
}

int main() {
  int a = 10;
  update(&a);
  printf("%d", a); // Outputs: 100
}

6. Pointer to Pointer

Double pointers store the address of another pointer. Used in dynamic memory and function references.

int x = 5;
int *p = &x;
int **pp = &p;

printf("%d", **pp);

7. Dynamic Memory Allocation

Memory can be allocated at runtime using malloc, calloc, and resized with realloc. Always free the memory.

int *p = (int*) malloc(sizeof(int));
*p = 25;
free(p);

8. Pointers and Strings

Character arrays and string literals are manipulated using pointers.

char *str = "Hello";
printf("%c", *(str+1)); // Outputs: 'e'

9. Pointers and Structures

Use -> to access members via structure pointers.

struct Student { int id; } s = {1};
struct Student *sp = &s;
printf("%d", sp->id);

10. Advanced Topics

void greet() { printf("Hello"); }
void (*fp)() = greet;
fp();

11. Applications in Data Structures

Pointers are essential for dynamic data structures like:

12. Common Mistakes and Debugging