如何通过在c中提升内存地址来存储结果

例1:

#include  #include  void saveData(void* data) // only allow to use void* data { // ...After some calculation: int inputData[5] = {1,2,3,4,5}; memcpy((int*)data, inputData, sizeof(inputData)); } int main() { int myNum[256]; saveData((void*)myNum); printf("\n%d%d%d%d%d\n",myNum[0],myNum[1],myNum[2],myNum[3],myNum[4]); } 

我在main中有一个int数组,并将数组传递给函数saveData,

在函数savaData中,我将inputData [5]保存到myNum [256];

它工作正常。

例2:

如果我有一个struct数组而不是int数组怎么办:

 #include  #include  struct Analysis{ int a; int b[10]; }; void saveData(void* data, size_t size) // update here for size param { struct Analysis a1; a1.a = 1; memset(a1.b, 0, 10*sizeof(int)); for(int i=0; i<10; i++) { a1.b[i] = 1; printf("%d", a1.b[i]); } struct Analysis a2; a2.a = 2; memset(a2.b, 0, 10*sizeof(int)); for(int i=0; i<10; i++) { a2.b[i] = 2; printf("%d", a2.b[i]); } //memcpy((int*)data, inputData, sizeof(inputData)); //How can I copy a1 and a2 into memory space of data(ana[2]) here; } int main() { struct Analysis ana[2]; saveData((void*)ana, sizeof ana[0]); // update here for(int i=0; i<2; i++) { printf("\n%d\n", ana[i].a); for(int j=0; j<10; j++) printf("%d", ana[i].b[j]); } } 

那么,如何在函数saveData中将a1和a2复制到ana [2]的内存中?

我的想法是:

我可以将数据(ana)转换为char *来遍历其地址并存储结果;

一旦我完成ana [0],我可以使用sizeof(ana [0])将指针前进到下一个

一个(ANA [1])。

****更新:——————————————– ————————

size – 这是用于保存每个文件的结果的结构的大小。 传递这些信息是很重要的。 如果没有此大小,您将无法正确访问已传递给映射的数组的插槽。 由于结果是一个void指针,为了支持多种类型的数组,常规指针算法将无法正常工作,因此大小在这里至关重要。

那么,如何在函数saveData中将a1和a2复制到ana [2]的内存中?

有很多方法。 一个是你用int演示它的方式的完全类比:

 void saveData(void* data) { // ...After some calculation: struct Analysis aa[2] = { { 1, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, { 2, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } } }; // note: no need to cast 'data' or 'aa' as long as a prototype is visible memcpy(data, aa, sizeof(aa)); } 

当然,当你的代码对其引用的类型和包含数组的容量(和存在)做出关键假设时,所有这些都会引发你为什么saveData()的参数声明为void *类型的问题。 感觉你过于通用了。

我的想法是:

我可以将数据(ana)转换为char *来遍历其地址并存储结果;

一旦我完成ana [0],我可以使用sizeof(ana [0])将指针前进到下一个(ana [1])。

是的,你可以做到,但为什么呢? 如果你要转换指针的类型,那么将它转换为你写入它的数据类型(例如struct Analysis * )并像数组一样使用它。 (还要注意,赋值运算符适用于struct s和union s。):

 void saveData(void* data) { // ...After some calculation: struct Analysis aa[2] = { { 1, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, { 2, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } } }; struct Analysis *data_array = data; for (int i = 0; i < 2; i++) { data_array[i] = aa[i]; } } 

这几乎与你所描述的相同,但更清晰,更清晰。