C - 空指针和偏移量

时间:2016-04-16 15:04:54

标签: c pointers

假设我有一个void指针(更像是;数组),我想要获取其中的项目。 因此,我知道指针[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
}

这个功能很好用,但唯一的问题是在main(..)结束时我得到了分段错误。我知道它是因为指针以及我如何访问它的项目,但我不知道如何纠正问题并避免分段错误。

2 个答案:

答案 0 :(得分:4)

正如@sunqingyao和@flutter指出的那样,你不能使用void指针算术,而是使用char *(一大块字节a qsort):< / p>

#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;
}

答案 1 :(得分:0)

引自N1570 6.5.6加法运算符(强调我的):

  

2另外,两个操作数都应具有算术类型,或者   一个操作数应该是指向完整对象类型的指针   其他应具有整数类型。 (增量相当于添加   1。)

显然,void不是完整的对象类型。因此,在+上应用void *运算符会调用未定义的行为,这可能会导致分段错误或其他任何操作。

解决问题的一种方法是将参数p声明为char *

相关问题