Print elements of array of void pointers
Sep 5, 2020 at 5:19pm UTC
Hello,
How can I fix this? I want to print all data in this array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# include <stdio.h>
int main()
{
void * myPointer[4];
int a = 10; float b = 30; char c = 'C' ; double d = 1.5;
myPointer[0] = &a;
myPointer[1] = &b;
myPointer[2] = &c;
myPointer[3] = &d;
printf_s("%d\n" , *(int *)myPointer);
printf_s("%f\n" , *(float *)(myPointer+1));
printf_s("%c\n" , *(char *)(myPointer + 2));
printf_s("%ld\n" , *(double *)myPointer + 3);
return 0;
}
Last edited on Sep 5, 2020 at 5:41pm UTC
Sep 5, 2020 at 5:30pm UTC
What is the type of (int*)*myPointer ?
What does the printf format specifier "%d" expect it to be?
Sep 5, 2020 at 5:42pm UTC
Thank you @Ganado,
I edited pointers in printf.
I want to cast like this.
1 2 3 4 5 6 7 8 9 10 11
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d" , *( (int *) p) );
p = &b;
printf("\nFloat variable is = %f" , *( (float *) p) );
return 0;
}
Sep 5, 2020 at 6:21pm UTC
hello, be guided by this example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
using namespace std;
int main()
{
int pointer[3][2] = {{1,2},{9,8},{14,21}};
int fil = (sizeof (pointer)/sizeof (pointer[0]));
int col = (sizeof (pointer[0])/sizeof (pointer[0][0]));
for (int i = 0; i < fil; i++)
{
for (int j = 0; j < col; j++)
{
cout<<pointer[i][j]<<endl;
}
}
}
Sep 5, 2020 at 6:44pm UTC
Hello Shervan360,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# include <stdio.h>
int main()
{
void * myPointer[4];
int a = 10; float b = 30; char c = 'C' ; double d = 1.5;
myPointer[0] = &a;
myPointer[1] = &b;
myPointer[2] = &c;
myPointer[3] = &d;
printf("%d\n" , *(int *)* myPointer); // Added "8" before "myPointer".
printf("%f\n" , *(float *)* (myPointer+1));
printf("%c\n" , *(char *)* (myPointer + 2));
printf("%g \n" , *(double *)* (myPointer + 3) ); // <--- Should match the 2 previous lines.
return 0;
}
Andy
Topic archived. No new replies allowed.