问题描述
我一直无法理解以下语句:
struct term {
int data;
char word[200];
};
void read_in_terms(struct term **terms,int *pnterms,char *filename);
该函数接收一个指向 struct term 的指针、一个指向 int 的指针以及一个类似城市.txt 格式的文件名。该函数为文件中的所有术语分配内存,并在 *terms 中存储一个指向块的指针。该函数将术语数存储在 *pnterms 中。该函数从文件名中读取所有术语,并将它们放在 *terms 指向的块中。
--
我已经附上了我认为这意味着什么的示意图。本质上,在堆中,我们为结构项的“数组”分配空间。并访问如下:
int main(void) {
int terms = 2;
int *pnterms = &terms;
struct term *term_list = (struct term *)malloc(sizeof(struct term) * (*pnterms));
(term_list+0)->data = 1000;
strcpy((term_list+0)->word,"hello");
(term_list+1)->data = 2000;
strcpy((term_list+1)->word,"bye");
printf("%s \n",(term_list+1)->word);
}
这样对吗?
解决方法
给定的描述基本上是正确的。 C 按值传递参数,而被调用函数必须修改的调用方作用域中的变量必须“按引用”传递。由于 C 中没有“引用”类型,这意味着传递一个指向变量的指针。
以下是使用 read_in_terms
重写的相同代码。
#include <malloc.h>
#include <string.h>
#include <stdio.h>
struct term {
int data;
char word[200];
};
void read_in_terms(struct term **terms,int *pnterms)
{
*pnterms = 2;
*terms = malloc(sizeof(struct term) * (*pnterms));
(*terms)[0].data = 1000;
strcpy((*terms)[0].word,"hello");
(*terms)[1].data = 2000;
strcpy((*terms)[1].word,"bye");
}
int main(void) {
int terms;
struct term *term_list;
read_in_terms(&term_list,&terms);
for(int n = 0; n < terms; n++)
printf("term[%d] data = %d,word = %s \n",n,term_list[n].data,term_list[n].word);
}
输出:
term[0] data = 1000,word = hello
term[1] data = 2000,word = bye