'Copying a certain number of characters from one pointer to another
I have a source pointer (pSource) and a goal pointer (pGoal). I also have a number of characters (n) that need to be copied to the pGoal from pSource.
I thought that I can just copy what's in the pSource to pGoal and move both pointers to the next location. (Both are pointing at the start at the beginning).
for (int i = 0; i < n; i++) {
pGoal+i = pSource+i;
}
Solution 1:[1]
Assuming that your pointers are of type char *, the correct way of doing this is:
for (int i = 0; i < n; i++) {
*(pGoal+i) = *(pSource+i);
// or pGoal[i] = pSource[i]
}
You can also check memcpy
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vasile_t |
