How to get the value from address?

No, I am not a novice in c - not at all! I have plenty of experience in c, c++, java etc. But I am facing a awkward problem in c (gcc in RHEL) - I am not able to get the value pointed by the pointer :wall: :wall:

Look at the following code -

#include <stdio.h>

int main()
{
    int i=100;
    int arr[2][3];
    arr[1][2]=&i;

    printf("a=%d\n",arr[1][2]); -> giving the address
    printf("b=%d\n",*(int *)(arr[1][2])); -> giving memory fault

}

How I can get the value? I am really clueless...

Thanks in advance ....

Are you running on a 64-bit system, or an embedded system? Either way, you cannot assume that a pointer will fit into an int. Either make your arr be an array of int pointers, or #include stdint.h and make it an array of type intptr_t.

If you still get the same problem, look at (or post) the output of this program:

#include <stdio.h>

int main()
{
    int i = 100;
    int arr[2][3];
    arr[1][2] = &i;

    printf("address: %p\n", &i);
    printf("value:   0x%x\n", arr[1][2]);
}

If you arent a novice in c then you should read up on pointers because arr[1][2] is not a pointer variable...meaning you cant assign an int to an int*.

Sure you can assign an int * to an int.

The result is undefined, and you just might get a segfault as a result if you then try to dereference the non-pointer that results..

Only if the OP casts it to the proper type...

arr[1][2] = (int) &i;

No I dont think there should be any runtime errors since i is a local variable and its address would be within the address space of the executing process.

Can you post any warnings you get when you compile this program.

You can assign an int* to an int since both are integer types. But you must be aware that an int may be smaller than an int* in your plataform (i.e, sizeof(int) < sizeof(int*) ). If this is the case, the value will be truncated and you probably will end up with an invalid pointer.

The UNIX System -- 64bit and Data Size Neutrality

I'm sure a long is enough to fit any pointer type on your platform. So, just change the arr type from int to long and you will get wat you want:

#include <stdio.h>

int main()
{
    int i=100;
    long arr[2][3];
    arr[1][2]=&i;

    printf("a=%p\n",(int*) arr[1][2]);
    printf("b=%d\n",*(int *)(arr[1][2])); /* will print 100 */

}