如 cmets 中所述,初始化指向 NULL 的指针允许您按照您的尝试测试值。下面是一个使用while 循环来测试father & mother 字符串值的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct child
{
char *father;
char *mother;
};
int main () {
struct child cont[10] = {{0}};
int i = 0;
memset(cont, 0, sizeof cont);
cont[0].father = strdup ("Mark");
cont[0].mother = strdup ("Lisa");
cont[1].father = strdup ("Tom");
cont[1].mother = strdup ("Fran");
while (cont[i].father && cont[i].mother)
{
printf ("cont[%d]\n father: %s\n mother: %s\n\n",
i, cont[i].father, cont[i].mother);
i++;
}
/* free memory allocated by strdup here */
return 0;
}
输出:
$ ./bin/structptr
cont[0]
father: Mark
mother: Lisa
cont[1]
father: Tom
mother: Fran
指向结构的指针数组
是的,您可以创建一个指向 struct 的指针数组,然后根据需要分配内存。这允许您测试if (cont[i])。本质上你在做同样的事情,但在第一种情况下,你声明了 10 个结构。在这种情况下,你永远不能只测试cont[i],因为它不是一个指针(更不用说它总是有一个地址,无论字符串是否填充)。
在这种情况下,您创建了 10 个指向所有设置为 NULL 的结构的指针(通过使用 calloc 而不是 malloc 来初始化它们)。当您实际使用 10 中的一个时,您为结构分配内存,给它一个在它之前为 NULL 的地址。这使您可以遍历 10 个指针以找出正在使用的指针。这是一种非常灵活的技术,可以应用于大量不同的数据结构。我希望它有所帮助。这是一个示例(相同的输出):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXS 10
struct child
{
char *father;
char *mother;
};
int main () {
/* create MAXS (10) pointers to child set to NULL */
struct child **cont = calloc (MAXS, sizeof(struct child*));
int i = 0;
cont[0] = malloc (sizeof(struct child)); /* allocate as needed */
cont[0]-> father = strdup ("Mark");
cont[0]-> mother = strdup ("Lisa");
cont[1] = malloc (sizeof(struct child)); /* allocate as needed */
cont[1]-> father = strdup ("Tom");
cont[1]-> mother = strdup ("Fran");
while (cont[i]) /* now simply test if pointer is not NULL */
{
/* you can check father/mother individually if desired
here we simply rely on printf outputting (null) if
either father or mother does not point to a string */
printf ("\ncont[%d]\n father: %s\n mother: %s\n",
i, cont[i]-> father, cont[i]-> mother);
i++;
}
/* free memory allocated to cont & by strdup here */
return 0;
}