Pointers, Arrays & Strings - Part 1
This section covers the fundamentals of pointers in C, including pointer declaration, dereferencing, and basic string manipulation using pointers.Understanding Pointers
A pointer is a variable that stores the memory address of another variable. Pointers are one of the most powerful features in C programming.Pointer Basics
Syntax:&- Address-of operator (gets the address of a variable)*- Dereference operator (accesses the value at the address)
Function Prototypes
Pointer Dereferencing
reset_to_98()
Updates the value of an integer through a pointer.nis a pointer to an integer*ndereferences the pointer to access the actual value- The value at the address is set to 98
swap_int()
Swaps the values of two integers using pointers.The
& operator is used to pass the address of variables to the function, allowing modification of the original values.String Manipulation with Pointers
In C, strings are arrays of characters terminated by a null byte (\0). Pointers provide an efficient way to traverse and manipulate strings.
_strlen()
Calculates the length of a string by incrementing a pointer.*saccesses the current characters++moves the pointer to the next character- Loop continues until null terminator (
\0) is found
_puts()
Prints a string followed by a newline.- Dereference pointer to get current character
- Print the character
- Move pointer to next position
- Repeat until null terminator
rev_string()
Reverses a string in place using array indexing.- Find the length of the string
- Use two indices: one at start (
j), one at end (i) - Swap characters at these positions
- Move indices toward center
- Stop when indices meet
String Copying
_strcpy()
Copies a string from source to destination.- Copies all characters including the null terminator
- Returns pointer to destination
- Allows function chaining
Common Use Cases
Passing Arrays to Functions
int *a and int a[] are equivalent in function parameters.
Pointer Arithmetic
Pointer arithmetic automatically accounts for the size of the data type.
ptr + 1 moves forward by sizeof(char) bytes.Memory Safety Tips
-
Always initialize pointers
-
Check for NULL before dereferencing
-
Don’t modify string literals
-
Array bounds checking
Key Takeaways
- Pointers store memory addresses
- Use
&to get an address,*to dereference - Strings are character arrays ending with
\0 - Pointer arithmetic enables efficient string traversal
- Always ensure buffers are large enough to prevent overflow
- Initialize pointers before use to avoid undefined behavior