【问题标题】:How to iterate on array of pointers to void如何迭代指向void的指针数组
【发布时间】:2019-08-24 09:45:48
【问题描述】:

我想做一个能够移位数组元素的函数,但数组可以是整数或我定义的结构。如何迭代指向 void 数组的指针?

到目前为止,这是我使用 Ints 的示例的代码,但我计划将相同的函数用于其他数据类型:

void shift(const void *source, int pos, int lenght){

    memmove(&source[pos], &source[pos+1], sizeof(int)*(lenght-pos-1) );
}

int main(int argc, char *argv[]) {
    int a[10] = {1,2,3,4,5,6};
    shift(a, 3, 10);

}

【问题讨论】:

  • “空数组”是什么意思?不包含任何值的数组?
  • 在 C 中,[..] 运算符充当 dereference。您不能取消引用 void 类型。您唯一真正的选择是将所有内容与sizeof (your_type) 一起转换为char*,并根据需要调整索引。
  • 我所说的 void 数组是指一个数组,其元素为 void*
  • 如果你有一个void * 的数组,你就会有一个void ** 类型的变量,但这不是你所拥有的。您需要准确显示此函数的调用方式。请使用minimal reproducible example 更新您的问题。

标签: c arrays void-pointers


【解决方案1】:

要在任意数据类型上进行这项工作,您需要做的就是传递数据的大小。这将让您计算偏移量。例如,

void shift(void *source, size_t size, int pos, int length){
    int src_offset =  pos * size;
    int dst_offset = (pos + 1) * size;
    memmove(source + src_offset, source + dst_offset, size*(length-pos-1) );
}

现在您可以像这样使用不同的数据类型

int main(int argc, char *argv[]) {
    // ints
    int a[10] = {1,2,3,4,5,6};
    shift(a, sizeof(int), 3, 10);

     // chars
    char b[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
    shift(b, sizeof(char), 3, 10);

     //etc...
}

【讨论】:

  • 感谢您的帮助。我尝试在 macOS 上运行它,它适用于 char 数组,但不适用于 int 数组。对于 int 数组,它给出([0] = 33554433, [1] = 50331648, [2] = 67108864, [3] = 83886080, [4] = 100663296, [5] = 0, [6] = 0, [7] = 0, [8] = 0, [9] = 0)。编译器还给出:警告:指向 void 的指针的算术是 GNU 扩展
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 2011-10-20
  • 2018-09-04
相关资源
最近更新 更多