Flyleaf
Flyleaf

Reputation: 39

getting values of void pointer while only knowing the size of each element

ill start by saying ive seen a bunch of posts with similar titles but non focus on my question

ive been tasked to make a function that receives a void* arr, unsigned int sizeofArray and unsigned int sizeofElement i managed to iterate through the array with no problem, however when i try to print out the values or do anything with them i seem to get garbage unless i specify the type of them beforehand

this is my function:

 void MemoryContent(void* arr, unsigned int sizeRe, unsigned int sizeUnit)
{
int sizeArr = sizeRe/sizeUnit;

for (int i = 0; i < sizeArr ; i++)
{
    
    printf("%d\n",arr); // this one prints garbage
    printf("%d\n",*(int*)arr); // this one prints expected values given the array is of int*
    arr = arr + sizeUnit;
}

}

the output of this with the following array(int arr[] = {1, 2, 4, 8, 16, 32, -1};) is:

-13296 1
-13292 2
-13288 4
-13284 8
-13280 16
-13276 32
-13272 -1

i realize i have to specify somehow the type. while the printf wont actually be used as i need the binary representation of whatever value is in there (already taken care of in a different function) im still not sure how to get the actual value without casting while knowing the size of the element any explanation would be highly appreciated!

note: the compiler used is gcc so pointer arithmetics are allowed as used

edit for clarification: the output after formating and all that should look like this for the given array of previous example

00000000 00000000 00000000 00000001 0x00000001
00000000 00000000 00000000 00000010 0x00000002
00000000 00000000 00000000 00000100 0x00000004
00000000 00000000 00000000 00001000 0x00000008
00000000 00000000 00000000 00010000 0x00000010
00000000 00000000 00000000 00100000 0x00000020
11111111 11111111 11111111 11111111 0xFFFFFFFF

Upvotes: 1

Views: 351

Answers (1)

chux
chux

Reputation: 153338

getting values of void pointer getting values of void pointer while only knowing the size of each element

Not possible getting values of void pointer while only knowing the size of each element.

Say the size is 4. Is the element an int32_t, uint32_t, float, bool, some struct, or enum, a pointer, etc? Are any of the bits padding? The proper interpretation of the bits requires more than only knowing the size.

Code could print out the bits at void *ptr and leave the interpretation to the user.

unsigned char bytes[sizeUnit];
memcpy(bytes, ptr, sizeUnit);
for (size_t i = 0; i<sizeof bytes; i++) {
  printf(" %02X", bytes[i]);
}

Simplifications exist.


OP's code void* arr, ... arr = arr + sizeUnit; is not portable code as adding to a void * is not defined by the C standard. Some compilers do allow it though, akin to as if the pointer was a char pointer.

Upvotes: 3

Related Questions