Reputation: 61
I am trying to build a program in C, which might receive any type of numeric array and a number to search in array, and will return its location.
Currently I get and error of " error: invalid use of void expression" for line#3 in the func
function.
Is the way I am trying to solve the issue even relevant? If not what should be the solution as I want to make as generic as possible?
The code is as follows:
void func(int,void*,double,int);
int main(){
/* arrays and numbers to search in each array*/
int arrInt[]={3,4,5,15,6,24,7,13,12};
double arrD[]={1.1,1.4,1.5,2.2,7.6,10.2};
long arrL[]={10,20,30,40,50,60};
int i2s=7;
double d2s=7.6;
long l2s=40;
func(sizeof(int*),arrInt,i2s,9);
func(sizeof(double*),arrD,d2s,6);
func(sizeof(long*),arrL,l2s,6);
}
void func(int size,void *arr,double num,int arrSize){
int i;
for(i=0;i<arrSize;i++){
if((double*)*arr==num)
return i+1;
arr=arr+size;
}
return -1;
}
Upvotes: 1
Views: 354
Reputation: 224342
The error you're getting is here:
(double*)*arr
You're attempting to dereference a void *
which is not allowed. You want to cast that pointer to a particular type and then dereference:
*(double *)arr
However, this still won't do what you want. For types other than double
, you'll be attempting to read a number of bytes as if they are a double
. Different types have different representations, so you can't take an address containing an int
, tell the compiler to read it as a double
, and expect to get anything meaningful out.
For this to work, you would need to pass the actual type to the function (or a value specifying a type). Types can't be passed in C, so you would need a flag:
enum searchTypes {
INT,
LONG,
DOUBLE
};
void func(int type, void *arr, double num, int arrSize){
int i;
for(i=0; i<arrSize; i++){
double val = 0;
switch (type) {
case INT:
val = ((int *)arr)[i];
break;
case LONG:
val = ((long *)arr)[i];
break;
case DOUBLE:
val = ((double *)arr)[i];
break;
}
if (val==num) {
return i+1;
}
}
return -1;
}
Then call it like this:
func(INT,arrInt,i2s,9);
func(DOUBLE,arrD,d2s,6);
func(LONG,arrL,l2s,6);
Upvotes: 0
Reputation: 726799
Dereferencing void*
in the condition below triggers the error:
if((double*)*arr==num)
Also, doing pointer arithmetic on void*
is not standard.
Even if you fix the syntax to dereference after pointer conversion, the comparison would fail unless you actually pass an array of double
s, so you need to change the approach.
You could fix the problem by passing a pointer to the search item, and doing the comparison using memcmp
:
int func(size_t size, void *arr, void* pnum, size_t arrSize) {
for (int i=0 ; i != arrSize ; i++, arr = ((char*)arr)+size ) {
if(memcmp(arr, pnum, size)==0)
return i+1;
}
return -1;
}
Note that now you need an address-of operator &
in the call, i.e.
int x = func(sizeof(int), arrInt, &i2s, 9);
Upvotes: 1