views:

84

answers:

4

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: 

Nevermind...it's obviously too late.

To solve, change

 *a_ptr = (int)&b_ptr;

to

*a_ptr = (int)b_ptr; 
CrypticPrime
Why are you even going via `int`? Why `int *` when the actual objects are `char`? `char **a_ptr = (char **) *a_ptr = ` would make more sense.
caf
The reason is that I need the memory address of b[0], not the value. A pointer won't fit inside of a char as it is generally 4 bytes and a char is 1. Int is 4 bytes.
CrypticPrime
+3  A: 
*((int*) a_ptr) = (int) b_ptr; 
Tristan Su
`a_ptr` is already an `int *`. No need to cast it. `*a_ptr = (int) b_ptr`.
AndreyT
yes. i didn't see it right.
Tristan Su
A: 
Tony
"you'll pick up other values beside the char". This is exactly what I want. These are effectively byte arrays storing an arbitrary number of types - not single chars. Think of b[0] as a buffer. If I want to store an int at b[0], then it would use b[0]-b[3]. Which is what I want. That is why I need the address of b[0]. I can return the address of b[0], which is stored at a[0], so tht the calling function (which knows the type) knows how many bytes to read/write to b[];
CrypticPrime
A: 

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;
    }
Chubsdad
Unfortunately, a and be must remain as is per the assignment.
CrypticPrime