How to use void * variable?

Today I found I didn’t know how to use void * variable, so I think I need to write it down.

Show you the code, which is compiled in Visual Studio 2017.



#include "pch.h"
#include <stdio.h>

#define raw 2
#define col 4
int number[raw][col] = { {1, 2, 3, 4},
			 {5, 6, 7, 8}};
void printData(void *data)
{
	int i = 0;
	for (i = 0; i < col; i++) {
		printf("%d\t", ((int *)data)[i]);
	}
	printf("\n");
}
int main()
{
	int i = 0;
	for (i = 0; i < raw; i++) {
		printData(&number[i]);
	}
}


Output:

1 2 3 4
5 6 7 8

So I believe you have already known that how to use void * variable.

We just need to explicit change its type to its origial.

void *data->>(int *)data or (char *)data or (double *)data

Have a good day. I am really appreciate it if you could tell me any feedback.

Share this article to your social media
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments