【问题标题】:Add struct to struct array using void pointer to said array in C使用指向C中所述数组的void指针将结构添加到结构数组
【发布时间】:2016-09-12 20:46:14
【问题描述】:

假设我有以下结构和该结构的数组:

struct Fileinfo {
  int ascii[128];  //space to store counts for each ASCII character.
  int lnlen;       //the longest line’s length
  int lnno;        //the longest line’s line number.
  char* filename;  //the file corresponding to the struct.
};

struct Analysis fileinfo_space[8]; //space for info about 8 files

我想要一个函数来向这个数组添加一个新的结构。它必须有一个 void 指针,指向将结构存储为参数的位置

int addentry(void* storagespace){
    *(struct Fileinfo *)res = ??? //cast the pointer to struct pointer and put an empty struct there
    (struct Fileinfo *)res->lnlen = 1; //change the lnlen value of the struct to 1
}

我的问题是:

  1. 什么可以代替???我按照this Stackoverflow 响应尝试了(Fileinfo){NULL,0,0,NULL}。但我得到 `error: ‘Fileinfo’ undeclared (first use in this function)

  2. 如何创建指向数组的空指针? (void *)fileinfo_space 是否正确?

我需要使用void * 作为此分配函数的参数。这不取决于我。

【问题讨论】:

  • 您有一个结构数组...除非您试图使数组更大,否则该结构已经存在(无需“添加”它)。只需将其成员设置为有意义的东西。
  • @quantumbutterfly:你什么意思?这是一个正常的数组取消引用和struct 成员访问。如果你还没有学过,看看你的 C 书。
  • 假设我有一个指向结构数组的空指针。如何使用它将第一个结构的 lnlen 值设置为 1?
  • 你不创建结构,它已经是数组的一部分。您可以像这样复制另一个结构的值:*(struct Fileinfo *)storagespace = otherstruct; 或像这样访问它的成员:((struct Fileinfo *)storagespace)->lnlen = 1;,或者执行struct Fileinfo *tmp = storagespace;,然后使用例如。 tmp->lnlen = 1; 等。顺便说一句,struct Analysis 是一个错误,还是您的数组实际上是不同类型的结构?
  • 如果您的编译器支持,您也可以使用*(struct Fileinfo *)storagespace = (struct Fileinfo){0};

标签: c


【解决方案1】:

假设你有一些内存块作为storagespace void 指针传递:

您必须定义一个能够初始化的常量(除非您使用的是 c++11),我们称之为init。顺便说一句,你的赋值是错误的:第一个成员是一个 int 数组。您不能将NULL 传递给它。只需将其填零,如下所示。

然后将你的void指针转换成你的struct上的指针,然后通过复制init struct进行初始化,随意修改...

int addentry(void* storagespace){
    static const struct Fileinfo init = {{0},0,0,NULL};
    struct Fileinfo *fi = (struct Fileinfo *)storagespace;
    *fi = init; //cast the pointer to struct pointer and put an empty struct there
    fi->lnlen = 1; //change the lnlen value of the struct to 1
}

【讨论】:

    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多