C 结构指针数组

C 结构指针数组,c,pointers,C,Pointers,所以我有3个文件:main.c、countries.h和countries.c 我在countries.h中声明名为“Country”的结构指针 我已经在countries.c和main.c中包含了countries.h 并在各国宣布了该结构 国家。h typedef struct Country* pCountry; countries.c struct Country { char *name; pCity cities; int numCities; pT

所以我有3个文件:main.c、countries.h和countries.c

我在countries.h中声明名为“Country”的结构指针

我已经在countries.c和main.c中包含了countries.h

并在各国宣布了该结构

国家。h

typedef struct Country* pCountry;
countries.c

struct Country {
    char *name;
    pCity cities;
    int numCities;
    pTerritory countryTerr;
};
现在,我想使用malloc创建Country结构的指针数组

所以我这样做了:

pCountry countries_array;
countries_array = (pCountry); 
malloc(num_of_countries*sizeof(countries_array));
为每个指针分配指针,即使malloc确实有效,但我做不到

使用[]为数组中的元素分配指针:

countries_array[0]= new_pointer;
我得到“未定义结构国家的无效使用”和“取消对指向未完成的指针的引用”

代码有什么问题


谢谢

看起来不错。只需将其分配给相同类型的内容,
struct Country
。此外,正如评论中指出的,它应该是malloc num_of_countries*sizeof
struct Country
(而不是指针类型),它现在正确地在下面被取消引用为sizeof(*countries_array),它也可以工作

pCountry countries_array;
countries_array = malloc(num_of_countries * sizeof (*countries_array));
struct Country Jefferson = {"Jefferson", 1,2,3 };
countries_array[0] = Jefferson;

// don't forget to free the memory when no longer needed.
free (countries_array);
如果我们必须将一个指针放入这个结构数组中,我们可以取消引用类似于countries\u数组[0]=*指针的指针,或者。。。我们可以将数组声明为指针数组,而不是结构数组。也许这就是你想要的。无论哪种方式,实际结构都必须在某个地方占用内存

pCountry *countries_array = malloc(num_of_countries*sizeof countries_array);
pCountry j = &Jefferson; // `&`, "address of" operator
countries_array[0] = j; // put a `pointer` into the array...

malloc()返回一个值。
malloc
itselfs返回指针,如果没有可用内存,则返回NULL,如:
countries\u array=malloc(num\u of\u countries*sizeof countries\u array)您将要查看:。什么是
国家\数组=(pCountry)应该是什么意思?这是下一行结果的类型转换吗?错误指向哪个文件,指向哪一行?
country\u数组的声明看起来如何?建议在malloc之后立即检查内存不足情况。如果(!countries_array){fprintf(stderr,“内存不足”);退出1;}在强制转换时
malloc()
。因为它被标记为“C”,所以我们不(强制转换)malloc的结果,因为这样做会隐藏重要的编译器错误。在C++中,它是必需的,所以它会有很大的收获。