SimC SimC - 6 months ago 143
Linux Question

GCC Warning: pointer arithmetic with type void *

I have to write a function, in C on Linux, to read or write generic data.

I can read (or write) big data so i made a while using how many bytes I read.
At the next call i, for example, read in the original pointer + how many bytes I read. But I don't know the type so I used a void * but gcc says:

membox.c: In function ‘myRW’:
membox.c:301:22: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]
w = read(fd, data + (s*type) , len - s);
^
membox.c:308:23: warning: pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]
w = write(fd, data + (s*type) , len - s);


Here is the code:

int myRW ( char op,int fd, void * data, size_t len, size_t type) {
size_t s = 0; // long int s = 0;
size_t w; // long int w;
//int err = 0;
if ( op == 'r') { // READ
while( s < len && !err){
w = read(fd, data + (s*type) , len - s);
if( w <= 0) return -1; //err = 1;
else s+=w;
}
}
else if ( op == 'w') { // WRITE
while( s < len && !err){
w = write(fd, data + (s*type) , len - s);
if( w <= 0) return -1; //err = 1;
else s+=w;
}
}
//if(err) return 1;
return 0;
}


Can i do this? I should ignore this warnings?

Answer

Cast the void * to char *. That way, you have an underlying type of size 1 to do pointer arithmetic on.

(char*)data + (s*type)
Comments