I am still learning the C programming language and trying out various
things with pointers, so please bare with me.
I have written a program which allows me to view the memory contents
using a pointer, I first started with this program.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_CHARS 4
typedef unsigned char BYTE;
void dump(BYTE *ptr);
int main(void) {
int offset = 0;
BYTE *ptr = NULL;
char *memory = NULL;
memory = (char *)malloc(sizeof(char) * MAX_CHARS);
*(memory+0) = 'T';
*(memory+1) = 'e';
*(memory+2) = 's';
*(memory+3) = 't';
for (offset=0; offset<MAX_CHARS; offset++) {
ptr = (BYTE *)memory+offset;
dump(ptr);
}
free(memory);
return 0;
}
void dump(BYTE *ptr) {
printf("%x %x (%03d) ",(unsigned int)ptr,*ptr,*ptr);
if (isprint(*ptr)) {
printf("[%c]\n",*ptr);
} else {
printf("[.]\n");
}
}
Output:
80a2008 54 (084) [T]
80a2009 65 (101) [e]
80a200a 73 (115) [s]
80a200b 74 (116) [t]
This works great, just how I expected, however when I change the
prgoram to use integers instead of chars:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_INTS 4
typedef unsigned char BYTE;
void dump(BYTE *ptr);
int main(void) {
int offset = 0;
BYTE *ptr = NULL;
int *memory = NULL;
memory = (int *)malloc(sizeof(int) * MAX_INTS);
*(memory+0) = 1;
*(memory+1) = 1;
*(memory+2) = 4;
*(memory+3) = 9;
for (offset=0; offset<MAX_INTS; offset++) {
ptr = (BYTE *)memory+offset;
dump(ptr);
}
free(memory);
return 0;
}
void dump(BYTE *ptr) {
printf("%x %x (%03d) ",(unsigned int)ptr,*ptr,*ptr);
if (isprint(*ptr)) {
printf("[%c]\n",*ptr);
} else {
printf("[.]\n");
}
}
Output:
8f2e008 1 (001) [.]
8f2e009 0 (000) [.]
8f2e00a 0 (000) [.]
8f2e00b 0 (000) [.]
As you can see this does not work in the same manner, I understand that
the char is 1-byte and the int is 4-bytes, but I thought when you increment
a pointer it incremented based on its data type.
I'm sure I'm doing something really dumb, can anyone please help?
Any assistance with this problem would be much appreciated.
Thanks