【发布时间】:2018-05-27 15:24:06
【问题描述】:
如问题所述,是否可以在函数中创建结构,然后在函数退出时返回该结构?由于在调用函数之前不会创建结构,因此我不知道在原型中放入什么作为返回值。任何建议/帮助都会很棒,谢谢。
static void section_to_segment_map(Elf *elf, GElf_Ehdr *ehdr) {
struct memory_data {
int phdr_addrs[ehdr->e_phnum][2];
int section_bounds[ehdr->e_shnum][2];
} memData;
for(int phead_cnt = 0; phead_cnt < ehdr->e_phnum; phead_cnt++) {
GElf_Phdr mem;
GElf_Phdr *phdr = gelf_getphdr(elf, phead_cnt, &mem);
memData.phdr_addrs[phead_cnt][1] = phdr->p_vaddr;
memData.phdr_addrs[phead_cnt][2] = phdr->p_vaddr + phdr->p_memsz;
}
printf("Starting and Ending Address Values for Program Segments:\n");
for(int i = 0; i < ehdr->e_phnum; i++)
printf("%x --> %x\n", memData.phdr_addrs[i][1], memData.phdr_addrs[i][2]);
Elf_Scn *scn = NULL;
for(int shead_cnt = 0; shead_cnt < ehdr->e_shnum; shead_cnt++) {
scn = elf_getscn(elf, shead_cnt);
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
memData.section_bounds[shead_cnt][1] = shdr->sh_addr;
memData.section_bounds[shead_cnt][2] = shdr->sh_addr + shdr->sh_size;
}
printf("\n");
printf("Starting and Ending Addresses for Program Sections:\n");
for(int j = 0; j < ehdr->e_shnum; j++)
printf("%x --> %x\n", memData.section_bounds[j][1], memData.section_bounds[j][2]);
return memData;
}
【问题讨论】:
-
您为什么要这样做?您的代码使用者将如何在结构上声明变量?
-
需要返回这两个数组以备将来在程序中使用。
-
你可以在函数外部声明结构体,或者传递指针或引用作为参数,以便函数可以修改传入的句柄数据
-
只要在函数外声明结构即可。这会更容易,这也是人们所期望的。
-
函数可以返回结构类型的值,但返回类型需要在函数声明之前完整声明。目前,您的
struct memory_data类型仅在函数内完全声明,因此您无法返回它。
标签: c data-structures struct return