Graphics Programs Reference
In-Depth Information
pointer.c
#include <stdio.h>
#include <string.h>
int main() {
char str_a[20]; // A 20-element character array
char *pointer; // A pointer, meant for a character array
char *pointer2; // And yet another one
strcpy(str_a, "Hello, world!\n");
pointer = str_a; // Set the first pointer to the start of the array.
printf(pointer);
pointer2 = pointer + 2; // Set the second one 2 bytes further in.
printf(pointer2); // Print it.
strcpy(pointer2, "y you guys!\n"); // Copy into that spot.
printf(pointer); // Print again.
}
As the comments in the code indicate, the first pointer is set at the begin-
ning of the character array. When the character array is referenced like this,
it is actually a pointer itself. This is how this buffer was passed as a pointer to
the printf() and strcpy() functions earlier. The second pointer is set to the
first pointer's address plus two, and then some things are printed (shown in
the output below).
reader@hacking:~/booksrc $ gcc -o pointer pointer.c
reader@hacking:~/booksrc $ ./pointer
Hello, world!
llo, world!
Hey you guys!
r eader@hacking:~/booksrc $
Let's take a look at this with GDB. The program is recompiled, and a
breakpoint is set on the tenth line of the source code. This will stop the
program after the "Hello, world!\n" string has been copied into the str_a
buffer and the pointer variable is set to the beginning of it.
reader@hacking:~/booksrc $ gcc -g -o pointer pointer.c
reader@hacking:~/booksrc $ gdb -q ./pointer
Using host libthread_db library "/lib/tls/i686/cmov/libthread_db.so.1".
(gdb) list
1 #include <stdio.h>
2 #include <string.h>
3
4 int main() {
5 char str_a[20]; // A 20-element character array
6 char *pointer; // A pointer, meant for a character array
Search WWH ::




Custom Search