C++ Notes: Pointers and Subscripts
Character strings
The string "Hello" is a char
array, and therefore a pointer to the first char of that
array, and therefore can be assigned to a char pointer.
Char operations often use pointers.
char* message; // message is a pointer to a char
message = "Hello"; // assigns the address of the first char
strcpy written with subscripts in simple style
This is at straight-forward solution with subscripts (altho better with do-while).
We'll make this a void function, altho the library function returns the
address of the first parameter.
void strcpy(char a[], const char b[]) {
int i = 0;
while (b[i] != 0) {
a[i] = b[i];
i++;
}
a[i] = 0; // put terminating 0 at end.
}
strcpy written with pointers in simple style
void strcpy(char* a, char* b) {
while (*b != 0) {
*a = *b;
a++;
b++;
}
*a = 0; // put terminating 0 at end.
}
strcpy written with subscripts, optimized slightly
Shorten by embedding assignment in if, and using fact that zero value is false.
void strcpy(char a[], const char b[]) {
int i = 0;
while (a[i] = b[i]) { // assignment, not comparison!
i++;
}
}
strcpy written with pointers in a cryptic style.
To make this really compact (but not more efficient) use postincrement operators.
C++ programmers often seem to like this insanely cryptic code,
but it isn't good style.
void strcpy(char* a, char* b) {while (*a++ = *b++);}