Array Manipulation
Basic String Operations
Manipulating null-terminated arrays involves several key techniques:
String Length Calculation
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "LabEx Programming";
size_t length = strlen(text);
printf("String length: %zu\n", length);
return 0;
}
String Copying
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[50];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
Advanced Manipulation Techniques
String Concatenation
#include <stdio.h>
#include <string.h>
int main() {
char first[50] = "LabEx ";
char second[] = "Programming";
strcat(first, second);
printf("Combined string: %s\n", first);
return 0;
}
Memory Management Strategies
graph TD
A[Allocate Memory] --> B[Perform Operation]
B --> C{Check Bounds}
C -->|Safe| D[Modify Array]
C -->|Unsafe| E[Potential Buffer Overflow]
Common Manipulation Methods
Method |
Function |
Description |
strlen() |
Length |
Calculates string length |
strcpy() |
Copying |
Copies one string to another |
strcat() |
Concatenation |
Combines two strings |
strncpy() |
Safe Copying |
Copies with length limit |
Safe Manipulation Example
#include <stdio.h>
#include <string.h>
void safe_copy(char *dest, size_t dest_size, const char *src) {
strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0'; // Ensure null-termination
}
int main() {
char buffer[10];
safe_copy(buffer, sizeof(buffer), "LabEx Rocks!");
printf("Safely copied: %s\n", buffer);
return 0;
}
Key Considerations
- Always check buffer sizes
- Use safe string manipulation functions
- Prevent buffer overflow
- Ensure null-termination after modifications
By mastering these techniques, developers can efficiently and safely manipulate null-terminated arrays in C programming.