Say I have a void pointer (more like; array), and I want to get the items inside it. So, I know that pointer[i] won't work since it's void and I don't know the type; I tried using the offset technique:
void function(void* p, int eltSize){
int offset = 3;
for(i = 0; i<offset; i++){
memcpy(p+(i*eltsize), otherPointer, eltSize);//OtherPointer has same type.
}
//End function
}
This function works good and everything, but the only problem is that at the end of main(..) I get segmentation fault. I know it's because of the pointer and how I accessed the items of it, but I don't know how to correct the problem and avoid segmentation fault.
As pointed out by @sunqingyao and @flutter, you can not use arithmetic with void
pointers in Standard C; instead, use a char *
(a chunk of bytes a la qsort
):
#include <stdio.h>
#include <string.h>
void function(void *ptr, size_t eltSize, void *otherPointer, size_t offset)
{
char *p = ptr;
for (size_t i = 0; i < offset; i++) {
memcpy(p + (i * eltSize), otherPointer, eltSize);
}
}
int main(void)
{
int arr[] = {1, 2, 3};
int otherValue = 4;
function(arr, sizeof *arr, &otherValue, sizeof arr / sizeof *arr);
for (int i = 0; i < 3; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
Quoted from N1570 6.5.6 Additive operators(emphasis mine):
2 For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)
Obviously, void
isn't a complete object type. Thus, applying +
operator on void *
invokes undefined behaviour, which may result in segmentation fault or anything else.
One approach to solve your problem would be declaring parameter p
as a char *
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.