Using void pointer to an array

Anusha Pachunuri picture Anusha Pachunuri · Jan 11, 2012 · Viewed 29.1k times · Source

I was just trying to use a void pointer to an integer array ,I tried to see if i can print the array back by casting it back into int. But it is giving me some random value. Can you tell me where i am going wrong?

#include<stdio.h>
#include<stdlib.h>

int main(){
    int a[5];
    int x;
    int j;

    a[0]=1;
    a[1]=2;
    a[2]=3;
    a[3]=4;

    void *arr=a;

    for(j=0;j<4;j++){
        x = *(int *)(arr+j);
        printf("%d",x);
    }
    return 0;
}

Output is this:

133554432131072512

Why is it not pinting elements of array a[] i.e 1,2,3,4 ?

Answer

ruakh picture ruakh · Jan 11, 2012

You need to cast arr before adding j. Here is a minimal fix:

x = *(((int *)arr)+j);

but I think it's clearer to write:

x = ((int *)arr)[j];