In C, strings and pointers are fundamentally intertwined. A string variable declared as a pointer (char *p) stores the memory address of the first character byte. Understanding pointer arithmetic and memory segments is essential for C memory management.
Pointer Arithmetic & String Processing Example
#include <stdio.h>
// Custom string copy function using pointer dereferencing
void custom_strcpy(char *dest, const char *src) {
while ((*dest++ = *src++) != '\0') {
// Copy byte by byte until null terminator is reached
}
}
int main(void) {
char source[] = "Systems Programming";
char destination[30];
custom_strcpy(destination, source);
printf("Copied String: %s\n", destination);
// Iterating through string using pointer arithmetic
const char *ptr = destination;
while (*ptr != '\0') {
printf("Char '%c' at address: %p\n", *ptr, (void*)ptr);
ptr++;
}
return 0;
}
Comments and corrections