有没有办法将未知类型的数组作为参数传递给 C 中的函数?

Alb*_*ert 2 c ansi-c

我一直在努力提高我的 C 技能和知识。今天我尝试创建一个接受任何类型数组的函数,但我还没有找到成功的方法,我正在使用 ANSI C 并且我尝试过将其作为 void 指针传递,但是当我尝试使用参数操作内存时,编译器会抱怨。有什么办法可以实现吗?我在想可能可以通过预处理器指令来完成,但我不确定。

PS:我的目标不是用数据填充数组,这只是一个函数,而是理解和学习如何在我不知道其类型的情况下传递数据,或者允许我的函数处理多种类型的数据数据。

这是编译过程的输出:

array_test.c:在函数“array_fill”中:

array_test.c:34:13:警告:算术中使用“void *”类型的指针 [-Wpointer-arith]

*(数组+ i)=数据;

^

array_test.c:34:5:警告:取消引用“void *”指针

*(数组+ i)=数据;

^~~~~~~~~~~~

array_test.c:34:5:错误:void 表达式的使用无效

*(数组+ i)=数据;

^

这是我的代码:

#include <stdio.h>

#define array_length(array) (sizeof(array)/sizeof(array[0]))

#define ARBITRARY_SIZE 10    

typedef enum
{
  false,
  true
} bool;

int array_fill(void*, int, int);

int main(int argc, char* argv[])
{
  int array[ARBITRARY_SIZE];
  int i;
 
  array_fill(array, array_length(array), 0);

  for(i = 0; i < array_length(array); i++)
  {
    printf("array[%d]: %d\n", i, *(array + i));
  }

  return 0;
} 

int array_fill(void* array, int size, int data)
{
  int i;
  
  for(i = 0; i < size; i++)
  {
    *(array + i) = data; 
  }

  /*I will implement a check later, in case of errors.*/
  return 0; 
}
Run Code Online (Sandbox Code Playgroud)

Inc*_*tic 5

指针指向内存中某个对象的开头。大多数指针还通过类型知道内存中该对象的大小,但void *.

例如,如果指向 32 位整数的指针的值为 0,则我们知道位 0 到 31 包含与该 32 位整数对应的数据。

0  31
|---| <- 32 bits storing the data for a 32-bit integer
Run Code Online (Sandbox Code Playgroud)

对于你的问题更重要的是,如果我们知道这个指针指向一个32位整数序列,我们就知道可以通过将指针向前移动32位来得到下一个整数。例如,第二个整数将从 32 开始。

0  31 32 63
|---| |---|

This is what int[2]. might look like in memory on a 32-bit system
Run Code Online (Sandbox Code Playgroud)

这就是指针算术的工作原理。对于 void 指针,void *array您不能这样做array++,甚至*array因为无法知道指针前进多少位或对应于多少位array。

0    ??
|----

We don't know how many bits a void pointer points to
Run Code Online (Sandbox Code Playgroud)

从技术上讲,您也可以通过传递对象的大小来解决这个问题,尽管这可能不是一个好主意。

// array points to the memory to be filled
// len is the number of elements in the array
// size is the size of an element (in bytes)
// fill points to an object to be used to fill array
void array_fill(void* array, int len, size_t size, void* fill) {
    // char is always a single byte
    char* byte_ptr = (char*) array;

    for (int i = 0; i < len; i++) {
        // Fill the current element
        memcpy(byte_ptr, fill, size);

        // Advance byte_ptr the correct number of bytes
        byte_ptr += size;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您不想使用,memcpy也可以手动将对象一次复制fill到一个字节。byte_ptr

  • 在 C 中不需要强制转换为 `(void*)`。`void *` 可以从任何指针类型分配(除了限定条件) (2认同)