I have a question about coding styles when using void pointers.
This code is modified from code geeks
#include<stdio.h>
int main()
{
int a[2] = {1, 2};
void *ptr = &a;
for(int i=0; i<2; i++) {
printf("%d\n", *(int *)ptr+i);
}
return 0;
}
I am using a generic circular buffer in my project. This buffer has a void pointer to a static buffer which is passed in during initialization. I want to traverse and print the data in the circular buffer. I was unsure how to print the contents until I found the code above.
I have two questions:
- Is this an appropriate well accepted way to traverse my data? Will tools such as PC-Lint throw a warning with good reason?
- Is there a better way to traverse this data?
Edit: Thanks to Lev M. I have updated my code to properly traverse the data using the size of the data type. The circular buffer is meant to be generic meaning we pass in a buffer and a data type size.
The updated test code is as follows.
#include<stdio.h>
int main()
{
int a[2] = {2, 1};
void *ptr = &a;
for(int i=0; i<2; i++) {
printf("%d\n", *(int *)ptr);
ptr = ptr + sizeof(int);
}
return 0;
}