Using void pointer to an array

后端 未结 4 1822
逝去的感伤
逝去的感伤 2021-01-01 02:20

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.

4条回答
  •  余生分开走
    2021-01-01 02:52

    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*). `

提交回复
热议问题