Damian Bedford Damian Bedford - 4 months ago 14
C Question

How do I initialize a char array with a memory address in C?

I'm in a sophomore C class and this project is about dealing with pointers and designing a memory dump function. So I've been able to struggle through the pointers and got a beginning and ending address to dump, even bitmasked it, and I wanted to initialize a char array with the beginning memory address. I initialize it with the same variable storing my masked beginning address but when I print the array, it contains a different memory address. Here's the function:

void memDump(void *base, int bytes)
unsigned char *begin;
begin = base;//beginning of range of memory
unsigned char *end;// ending range of memory
end = base + bytes;
int a, b;
long long int d=base;
d=d&0xFFFFF0; //trying to bitmask
long long int e=end;
e = e&0xFFFF0; //masked off the beginning and ending range
char c[16]={d}; //loop variables
printf("%x", c);

for (a=begin; a<=end; a+=16)
printf("\n%016X\n", d);
printf("%016X\n", a);
printf("%016X", e);


Sorry guys, i can't find something similar and this is my last resort. Thanks!

Update: Thanks for the insight everyone, reading some more about C and some articles on how to debug helped me out.


You cannot "initialize a char array" with some "memory address." A char array can only be initialized with characters.

Stackoverflow is not about doing your homework for you, so I will give you some advice, and then you can try implementing it. If you cannot put the advice into code, then you do not deserve to turn in a completed assignment.

First of all, once you have bitmasked your "d", you need to store it back into "begin", so that you have a pointer from which you can start reading bytes to dump.

This instruction:

printf( "%08p ", begin );

Will render the hexadecimal representation of your "begin" address in 8 characters, followed by a space. This is how you need to begin each row of your memory dump.

The instruction:

printf( "%02x ", *(begin++) );

gets the byte pointed by "begin", and renders the hexadecimal representation of that byte in two characters, followed by a space. It then increments "begin", to point to the next byte. You need to do this 8 or 16 times, depending on how wide you want your memory dump to be, then do a printf( "\n" ) to move to the next line.

Then you need to keep repeating the above until your "begin" has exceeded your "end". (So, you are looking at an outer loop, for each row, and an inner loop, for each byte within the row.)

I hope this helps.