我一直在努力提高我在 C 方面的技能和知识。今天我试图创建一个接受任何类型数组的函数,但我还没有找到成功的方法,我正在使用 ANSI C我试图将它作为空指针传递,但是当我试图遍历使用参数操作的内存时,编译器会提示。有什么办法可以实现吗?我在想这可能可以通过预处理器指令来完成,但我不确定。
P.S:我的目标不是用数据填充数组,这只是一个函数,而是理解和学习如果我不知道数据类型如何传递数据,或者让我的函数不仅可以处理更多一种数据。
这是编译过程的输出:
array_test.c: In function 'array_fill':
array_test.c:34:13: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
*(array + i) = data;
^
array_test.c:34:5: warning: dereferencing 'void *' pointer
*(array + i) = data;
^~~~~~~~~~~~
array_test.c:34:5: error: invalid use of void expression
*(array + i) = data;
^
这是我的代码:
#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;
}
最佳答案
指针指向内存中某个对象的开头。 大多数 指针还通过类型知道该对象在内存中的大小,void *
除外。
例如如果指向 32 位整数的指针的值为 0,我们知道位 0 到 31 包含与该 32 位整数对应的数据。
0 31
|---| <- 32 bits storing the data for a 32-bit integer
对于你的问题更重要的是,如果我们知道这个指针指向一个 32 位整数序列,我们就知道我们可以通过将指针向前移动 32 位来获得下一个整数。例如。第二个整数将从 32 开始。
0 31 32 63
|---| |---|
This is what int[2]. might look like in memory on a 32-bit system
这就是指针算法的工作原理。使用空指针 void *array
你不能做 array++
甚至 *array
因为没有办法知道指针前进多少位或者有多少位对应array
。
0 ??
|----
We don't know how many bits a void pointer points to
您也可以技术上通过传递对象的大小来解决这个问题,尽管这可能不是一个好主意。
// 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;
}
}
如果您不想使用 memcpy
,您也可以手动将 fill
对象复制到 byte_ptr
,一次一个字节。
关于c - 有没有办法将未知类型的数组作为参数传递给 C 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100578/