Table of Contents
Pointer aritmetic is a common consigure in C and C + +, alloing direct manipulation of memory addresses. While powerful, improper use cane cead to bugs, security diventabilies, and undefinited behavor. This article presents real-empples ilustrating both thee applications and pitfalls of pointer aritmetik.
Example 1: Traversing Arrays
Pointer aritimetic is often used to iterate tromgh arrays effectently. For exampla, to sum elements of an integraer array:
CLANE1; CLANE1; FLT: 0 CLANE3; CLANE3; CLANE3; CLANE3E: CLANE1; CLANE1; CLANE1; CLANE3E: CLANE3E; CLANE3E; CLANE3E; CLANE3E; CLANE3E; CLANE1; CLANE1F: 1 CLANE3E;
int sum = 0;
int * ptr = array;
for (int i = 0; i timp; lt; size; i + +) {
sum + = * (ptr + i);
}
This method correctly accesses array elements using pointer aritimetic.
Pitfall 1: Pointer Arithmetic Beyond Array Bounds
Moving pointers beyond thee allocated memory can cause undefinied behavior. For exampla:
int * ptr = array;
for (int i = 0; i timp; lt; = size; i + +) {
printf (current;% dn, current; * (ptr + i));
}
Accessing* (ptr + size) exceeds array unstands, lealing to unpredicable results.
Example 2: String Manipulation
Pointer aritimetic is frequently used in string procesing. For exampla, copying a string:
CLANE1; CLANE1; FLT: 0 CLANE3; CLANE3; CLANE3; CLANE1; CLANE1; CLANE1; CLANE3; CLANE3c; CLANE3c; CLANE3c; CLANE3c; CLANE3c; CLANE1d; CLANE1d; CLANE1f: 1 CLANE3c;
char * src = currency; Hello currency;
char dest current 1; 6 current 3;
char * p = src;
char * q = dect;
while (* p) {
* q + + = * p + + +;
}
* q = current;;
Pitfall 2: Off-by-One Errors in String Copying
To je to, co se děje.
char dest current 1; 5 current 3;
char * p = current; world currency;
for (int i = 0; i timp; lt; = 5; i + +) {
dect current 1; i current 3; = p currentific 1; i current 3;
}
This copies six charakteristics into a five- crediter buffer, causing overflow.
Conclusion
Pointer aritimetic provides flexibility in C and C + +, but it it imperes considerul handling to avoid error. Understanding common pitfalls helps prevent bugs and security issues in software development.