【发布时间】: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
}
我的问题是:
什么可以代替???我按照this Stackoverflow 响应尝试了
(Fileinfo){NULL,0,0,NULL}。但我得到 `error: ‘Fileinfo’ undeclared (first use in this function)如何创建指向数组的空指针? (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