Using void pointer to an array

纵然是瞬间 提交于 2019-11-30 17:11:41

问题


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 ?


回答1:


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];



回答2:


You are doing pointer arithmetic on void * which is not valid in C.

In GNU C (C with gcc extensions), it is actually permitted and the sizeof (void) is considered to be 1.

http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

"addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1."




回答3:


you should not add numbers to void pointers. cast it before. (x = *((int *)arr+j);)

When you add number to a pointer, the compiler multiply this number with the size of the type that is pointed, so if you add number to a pointer to wrong type, you will get wrong result.

if I remember correct, add to void* is illegal, but some compilers adds the exact number in bytes (like it is char*). `




回答4:


The C standard does not define behaviour for arithmetic of void *, so you need to cast your void * to another pointer type first before doing arithmetic with it.

Some compilers [as an extension] treat pointer arithmetic of void * the same as char *, so each ‘+1’ will only increase the address by 1, rather than by the size of the pointed-to object. This is not standardised though so you can't rely on this behaviour.



来源:https://stackoverflow.com/questions/8812690/using-void-pointer-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!