C-空指针和偏移量 [英] C - Void pointer and offset

查看:170
本文介绍了C-空指针和偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个空指针(更像是数组),我想在其中获取项目. 因此,我知道指针[i]无效,因为它是空的,我也不知道类型.我尝试使用偏移技术:

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
}

此函数可以正常运行,但所有问题都存在,但是唯一的问题是在main(..)末尾出现了分段错误.我知道这是因为指针以及我如何访问它的项,但我不知道如何解决该问题并避免出现分段错误.

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.

推荐答案

如@sunqingyao和@flutter所指出的那样,您不能在标准C中对void指针使用算术运算.相反,请使用char *(一小部分字节为qsort):

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

这篇关于C-空指针和偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆