Hello,
I'm experimenting with using void pointers as function parameters but I've hit upon a bit of a problem when I pass in an array to a function which uses such pointers. Here's my code:
Code:
#include <stdlib.h>
#include <stdio.h>
#define ARRAYSIZE 10
void voidfunc(void*);
const int SIZEOFINT = sizeof(int);
int main(int argc, char **argv){
int number[ARRAYSIZE] = {0,1,2,3,4,5,6,7,8,9};
int i;
printf("The Size of int is %i\n",sizeof(int));
printf("From the Main():\n");
for (i = 0; i<ARRAYSIZE;i++){
printf("number[%i] is %i\n",i,number[i]);
}
voidfunc(number);
printf("From the Main():\n");
for (i = 0; i<ARRAYSIZE;i++){
printf("number[%i] is %i\n",i,number[i]);
}
}
void voidfunc(void* array){
int i;
int intarray[ARRAYSIZE];
//intarray[] = (int*)array;
printf("From the voidfunc():\n");
for (i = 0; i<ARRAYSIZE;i++){
*(int*)(array+(i*SIZEOFINT)) = *(int*)((int)array+(i*SIZEOFINT)) + 1;
printf("number[%i] is %i\n",i,*(int*)((int)array+(i*SIZEOFINT)));
//printf("number[%i] is %i\n",i,intarray[i]);
}
}
Now the 'problem' occurs in voidfunc(). As you can see I have to use pointer arithmetic to get at the array values i.e.
*(int*)(array+(i*SIZEOFINT)) = *(int*)((int)array+(i*SIZEOFINT)) + 1;
i*SIZEOFINT takes care of the size of each array element but I'd like to try and get away from this kind of coding if possible and use typical array access methods i.e. array[index].
So is there anyway in voidfunc() that I can cast array as a pointer to an array. Everything I try to does not produce the correct result. Using [] typically indexes the array with the incorrect element size or just won't compile.
Can anyone give me any advice?
thanks