[英]C - Void pointer and offset
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] 不会工作,因为它是空的,我不知道类型; 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.这个函数一切正常,但唯一的问题是在 main(..) 结束时我得到了分段错误。 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;正如@sunqingyao 和@flutter 所指出的,标准C 中不能使用带有
void
指针的算术; instead, use a char *
(a chunk of bytes a la qsort
):相反,使用
char *
(一大块字节 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):引自 N1570 6.5.6 Additive operators(强调我的):
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.
2 对于加法,要么两个操作数都为算术类型,要么一个操作数为指向完整对象类型的指针,另一个操作数为整数类型。 (Incrementing is equivalent to adding 1.)
(递增相当于加 1。)
Obviously, void
isn't a complete object type.显然,
void
不是一个完整的对象类型。 Thus, applying +
operator on void *
invokes undefined behaviour, which may result in segmentation fault or anything else.因此,在
void *
上应用+
运算符会调用未定义的行为,这可能会导致分段错误或其他任何问题。
One approach to solve your problem would be declaring parameter p
as a char *
.解决您的问题的一种方法是将参数
p
声明为char *
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.