Issue getting and storing memory address in array
开发者_Python百科So, I'm having a bit of pointer issues. I'm writing a function that stores memory addresses in a[]. These memory addresses point to actual data values in b[]. I'm having trouble getting the memory address from b to store in a.
// Assume these are initialized to 0 outside of this snippet
char a[100];
char b[100];
b[0] = 42; // Some value for us to use
int* a_ptr = (int*)&a[0]; // Store the address of a[0] in a_ptr
int* b_ptr = (int*)&b[0]; // Store the address of b[0] in b_ptr
*a_ptr = (int)&b_ptr; // PROBLEM LINE. The first four bytes of a[]
// should contain the memory address of b[0].
// However, it does not. Here are the debugger values:
// a_ptr = 0x00429148
// b_ptr = 0x00429151
// a[0] SHOULD be 0x00429151, but it is instead 0x0012fe4c.
Is there some trick I need to do to get 0x00429151 to be stored at a[0..3]?
*a_ptr = (int) b_ptr;
updated per comments
Nevermind...it's obviously too late.
To solve, change
*a_ptr = (int)&b_ptr;
to
*a_ptr = (int)b_ptr;
Yikes - what a mess. If a and b are arrays of char, then you don't want to create ints to them... an int is a bigger memory area than a char, and when you read you'll pick up other values beside the char and end up with an effectively random value. If you try to store to the int, you'll clobber the char's value (possibly with an unintended value), while clobbering several values around it.
It's a very good idea not to use C-style casts (e.g. "(int*)") while learning C++. If you use static_cast<> the compiler can tell you when you've made a big mistake.
So, what you want is:
char* p_a = &a[0]; char* p_b = &b[0]; *p_a = *p_b; // copy
Though there are better ways to do this, this probably is the closest to your approach
int main(){
char *a[100]; // not char but char *
char b[100];
b[0] = 42; // Some value for us to use
char** a_ptr = (char **)&a[0]; // Store the address of a[0] in a_ptr
char* b_ptr = (char*)&b[0]; // Store the address of b[0] in b_ptr
*a_ptr = b_ptr;
}
精彩评论