本文介绍了在C中将任意对象存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,但我想把头放在试图将任意对象存储在数组中。结构,整数,字符,函数等。基本上,某些东西可能会沿(伪代码)使用空指针:

I am new to C but am trying to wrap my head around trying to store arbitrary objects in an array. Structs, integers, chars, functions, etc. Basically something perhaps using void pointers along the lines of (pseudocode):

void *array[] = malloc(10000);
struct MyStruct m = malloc(sizeof(m));
int x = 10;
char c[] = "Look Here";
array[0] = &m;
array[1] = &x;
array[2] = &c;

基本上,我想要一个全局数组来存储任意对象,就像数据库一样,然后获取它们

Essentially I want to have a global array store arbitrary objects sort of like a database, and then fetch them by index somehow.

void *global_array[];

void
get_from_array(int index, void *ptr) {
  *ptr = global_array[index];
}

int
main() {
  global_array = malloc(10000);
  struct MyStruct m = malloc(sizeof(m));
  int x = 10;
  char c[] = "Look Here";
  global_array[0] = &m;
  global_array[1] = &x;
  global_array[2] = &c;
  struct MyStruct m2;
  get_from_array(0, &m2);
  assert(m == m2);
}

是否可能这样?

推荐答案

是。您可以创建一个void双指针 void ** 并使用malloc为它分配(例如10000个)void指针的空间。它可以被索引,并有效地用作 void * 类型的数组

Yes. You can create a void double pointer void** And allocate it space of (say 10000) void pointers with malloc. It can be indexed and it effectively acts as an array of void* type

对于您提到的代码,就像是

For the code mentioned in your question, it would be something like

# include <stdio.h>
# include <stdlib.h>


void **array;

typedef struct MyStruct{
  int a;
  char b;
}MyStruct;

int main()
{
  array = malloc(sizeof(void*)*10000);
  struct MyStruct* m = (MyStruct*)malloc(sizeof(MyStruct));
  m->a=1;
  m->b='x';
  int x = 10;
  char c[] = "Look Here";
  array[0] = m;
  array[1] = &x;
  array[2] = &c;
  printf("%d %c\n%d\n%s\n",((MyStruct*)(array[0]))->a,((MyStruct*)(array[0]))->b,*(int*)(array[1]),(char*)(array[2]));
  return 0;
}

这篇关于在C中将任意对象存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:29