【发布时间】:2020-06-06 09:20:08
【问题描述】:
我有一个函数可以将输入文件解析为单独的页面。 other_func 将行添加到这些页面。这是函数的简化版本。
void func(FILE* f, page** p_pages, int* page_count) {
... do stuff, before passing a line struct and the current page to another function.
page* p = *p_pages;
int n = *page_count - 1;
other_func(line, &p[n]);
}
在最后三行中,我试图传递当前页面的地址。我以为我可以使用 &*p_pages[page_count - 1] 之类的东西来做到这一点,但我似乎无法让它工作(我认为出现 EXC_BAD_ACCESS 错误......)。
有没有更短的方法来写这 3 行?
编辑:添加更多实际代码。
/* struct declarations */
typedef struct page page;
typedef struct line line;
struct page {
char* title;
char* filename;
page* parent;
line* lines;
int numlines;
};
struct line {
char type;
char* text;
};
/* relevant functions */
void addLineToPage(line l, page* p) {
p->numlines++;
p->lines = realloc(p->lines, sizeof(line) * p->numlines);
p->lines[p->numlines - 1] = l;
}
void parse_file(FILE* file, page** p_pages, int* page_count) {
char* rawline = 0;
while( (rawline = p_getline(file)) ) {
char rune = 0;
int n;
sscanf(rawline, "%c %n", &rune, &n);
remove_char(rawline, '\n');
char* text = rawline + n;
if (rune == '\n') {
continue;
} else if (!strchr(PI_RUNES, rune)) {
*page_count = *page_count + 1;
*p_pages = realloc(*p_pages, sizeof(page) * *page_count);
int len = (int) strlen(rawline) + 1;
char* fn = (char*) malloc(len * sizeof(char));
string_to_filename(rawline, fn);
page* p = *p_pages;
int address = *page_count - 1;
p[address] = (page) { .title = rawline, .filename = fn, .parent = NULL, .lines = NULL, .numlines = 0 };
} else {
line l = { .type = rune, .text = text };
addLineToPage(l, *p_pages + *page_count - 1);
}
}
}
【问题讨论】:
-
你想要
&(*p_pages)[*page_count - 1]。括号是必需的,你需要取消引用page_count。 -
你能发布
page和other func类型的声明吗?你怎么称呼func,换句话说minimal-reproducible-example -
@TomKarzes:或者他可以这样做
other_func(line, *p_pages + *page_count - 1) -
@alk 是的,
*p_pages + *page_count - 1是等价的。 -
保持原样。这样就完美了。绝对没有必要将尽可能多的动作塞进一行。 (嗯,并不是很完美。完美的是从您的函数中返回一个值。
realloc不接受任何臭双指针,这绝非偶然。)
标签: c pointers dereference