假设我有一个空指针(更像是;数组),我想获取其中的项目。所以,我知道指针 [i] 不会工作,因为它是空的,我不知道类型;我尝试使用偏移技术:
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
}
Run Code Online (Sandbox Code Playgroud)
这个函数一切正常,但唯一的问题是在 main(..) 结束时我得到了分段错误。我知道这是因为指针以及我如何访问它的项目,但我不知道如何纠正问题并避免分段错误。
正如@sunqingyao 和@flutter 所指出的,void在标准C 中不能使用带有指针的算术;相反,使用 a 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;
}
Run Code Online (Sandbox Code Playgroud)