Pointers, Arrays & Strings - Part 3
This section covers low-level memory manipulation functions and advanced pointer operations including direct memory access, memory copying, and working with multi-dimensional arrays.Function Prototypes
Memory Manipulation Functions
These functions operate on raw memory, treating data as bytes rather than specific types._memset()
Fills a block of memory with a constant byte value.s- Pointer to memory blockb- Byte value to setn- Number of bytes to set
memset operates byte-by-byte. For non-char types, use with caution:_memcpy()
Copies bytes from source to destination memory block.- Copies exactly
nbytes - Does not check for null terminators
- Works with any data type
- Faster than string functions for large blocks
String Searching Functions
_strchr()
Locates the first occurrence of a character in a string.- Pointer to first occurrence of
c NULLif character not found
_strspn()
Calculates the length of the initial segment consisting only of characters from a specified set.s that consist only of characters from accept.
Examples:
_strpbrk()
Locates the first occurrence of any character from a set.s for the first occurrence of any character from accept.
Example:
_strstr()
Locates a substring within a string.- Pointer to the beginning of the substring
NULLif substring not found
- For each position in haystack
- Try to match the entire needle
- If complete match found, return starting position
- Otherwise, move to next position
Multi-Dimensional Arrays
Multi-dimensional arrays are arrays of arrays. Understanding pointer notation is crucial.print_chessboard()
Demonstrates working with 2D arrays using pointer notation.char (*a)[8]- pointer to an array of 8 charsa[i][j]- equivalent to(*(a + i))[j]- Each
a[i]is an array of 8 characters
Different pointer notations for 2D arrays:
Advanced Pointer Arithmetic
Navigating 2D Arrays
Pointer to Array vs Array of Pointers
Performance and Memory Considerations
memcpy vs strcpy
Memory Initialization
Common Pitfalls
1. Overlapping Memory in memcpy
2. memset with Non-Zero Values for Integers
3. Forgetting NULL Check
Key Takeaways
memsetfills memory with a byte value (use for zero initialization)memcpycopies raw bytes without checking content- Never use
memcpyon overlapping memory regions - String search functions return pointers or NULL
strchrfinds characters,strstrfinds substringsstrspncounts matching prefix characters- Multi-dimensional arrays use pointer-to-array notation
char (*a)[8]is different fromchar *a[8]- Always check return values for NULL before dereferencing
- Memory functions are faster but less safe than string functions