I am attempting to create a function that assigns memory and checks to see if the memory allocation has been accomplished. To allow any memory type to be assigned I have set the function to accept void like so: foo(void ***memory, size_t pointer_type)
. The intention here is to allow the user to input any pointer into the first section and then the size of the pointer type in the second to allocate correctly, such as:
int foo(void ***memory,size_t pointer_type)
{
void **temp;
if((temp=calloc(10,pointer_type))==NULL)
{
return(-1);
}
for(i=0;i<10;i++)
{
if((temp[i]=calloc(10,pointer_type))==NULL)
{
// free array as can't be used
for(i;i>=0;i--)
{
free(temp[i]);
temp[i]=NULL;
}
free(temp);
temp=NULL;
return(-1);
}
}
*memory=temp;
return(0);
}
int main()
{
double **pointer;
if(foo(&pointer, sizeof(double))==-1)
{
return(-1);
}
//do stuff then free memory
return (0);
}
In this example an array of doubles should be created. I came upon this idea when reading other SE posts explaining that this allows any array type to be created, however the compiler gives the following warning :
warning: passing argument 1 of 'foo' from incompatible pointer type note: expected
void ***'
but argument is of type'double ***'
This suggests to me that something I have done is incorrect, however when treating the array as a double array after allocation everything works fine so I am lost as to what to do.
EDIT: Ok so the use of the 3-star is to assign the memory from a separate function for a 2D array and was how I was shown to do it, ie if I used pointer[a][b]=10
then it would act like a 2D array. If there are better ways then please do show an example, however I still require the array to be of any type which currently is the pressing matter.