Adh*_*esh 0 c arrays struct pointers
我想在struct中有一个数组,它将存储相同数据类型(即struct map)的指针.我查看了Stackoverflow,发现了这个:
struct map {
int city;
struct map **link = (struct map *)malloc(204800 * sizeof(struct map *));
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了这个错误: -
error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
struct map **link = (struct map *)malloc(204800*sizeof(struct map *));
Run Code Online (Sandbox Code Playgroud)
这是一个struct定义,你不能malloc或在声明中使用任何函数,因为声明不会被执行,它只是一种关于'map'类型的结构应该是什么样的模板,编译器会这样知道在创建它的实例时应该为struct map分配多少内存.
当你想在struct map中使用成员时(例如使指针链接指向一些可行的内存段)你需要在某处创建一个'map'实例,然后你才能调用malloc并使链接指向结果内存段.
解决这个问题的方法是首先声明结构如下:
struct map{
int city;
struct map **link;
};
Run Code Online (Sandbox Code Playgroud)
当你在main中创建struct的实例时,你可以为链接分配空间,如下所示:
int main()
{
struct map *temp = malloc(sizeof(struct map));
temp->link = malloc(204800*sizeof(struct map *));
return 0;
}
Run Code Online (Sandbox Code Playgroud)