Printing void pointer values

I have a funciton that returns a void pointer. Suppose I know that the data block that it points to is an array of ints. How can I print them?

From another thread, I saw that I selected void as my desired data type as follows:

printf("%i",*((int*)data)); 

But, as I said, the data is an array of ints. I tried to do this, but this is not a valid expression:

 for(i = 0; i<3; i++){ printf("%i \n", *((int*)(data+sizeof(int)*i))); } 

What is the correct way to print?

+4
source share
2 answers

Just use a temporary int* :

 int *p = data; for (int i=0; i<3; i++) printf("%i\n", p[i]); 

Note that there is no explicit translation in the first line, because something unnecessary with void* and avoiding explicit casts is considered a good C style. Inside the loop, I used the fact that you can index the pointer to an array as if it were an array.

+5
source

Your initial attempt is incorrect in "formal" C, as pointer arithmetic does not apply to void * pointers. However, some compilers support pointer arithmetic on void * pointers as a non-standard extension (GCC is a notable example). In such void * compilers, pointers are treated as char * pointers for arithmetic purposes. And yours

 for(i = 0; i < 3; i++) printf("%i\n", *((int *) (data + sizeof(int) * i))); 

will work in such a compiler as intended.

With a more pedantic compiler, you can save the day by doing

 for(i = 0; i < 3; i++) printf("%i\n", *((int *) ((char *) data + sizeof(int) * i))); 

But in any case, the above two pieces of code are hopelessly complex. They have some meaning as examples when you just study pointer arithmetic, but that’s all that’s good for them.

What you really need is just

 for(i = 0; i < 3; i++) printf("%i\n", ((int *) data)[i]); 

You can enter an optional int * pointer, like the other suggested answers, to make your code even more readable. But it is up to you.

+2
source

Source: https://habr.com/ru/post/1484735/


All Articles