如何解决通过指针数组引用的结构
我正在尝试设置指向结构的指针数组。我尝试了两 (2) 种方法,但都给我编译错误。下面的代码示例。
如有任何帮助,我们将不胜感激。
在第一个例子中,我得到一个编译警告
struct stPlanets *pPlanets = &planets;
警告是:
警告:从不兼容的“struct stPlanets ”初始化 指针类型‘struct stPlanets ()[5]’ [-Wincompatible-pointer-types] struct stPlanets *pPlanets = &planets;
示例 01。
#include <stdio.h>
int main(void)
{
struct stPlanets {
char *planet;
char *deity[10];
};
struct stPlanets planets[] = {
{"Mercury",{"Messenger"}},{"Venus",{"Love,Beauty"}},{"Earth",{"Earthly things"}},{"Mars",{"War"}},{"Jupiter",{"Sky,Thunder,King of gods"}}
};
struct stPlanets *pPlanets = &planets;
int i = 0;
int sPlanets = sizeof(planets) / sizeof(struct stPlanets);
printf("There are %d planets.\n",sPlanets);
for (i = 0; i < sPlanets; i++)
{
printf("%-10s : %s.\n",planets[i].planet,planets[i].deity[0]);
}
return 0;
}
示例 02。
#include <stdio.h>
int main(void)
{
struct stPlanets {
char *planet;
char *deity[10];
};
struct stPlanets *planets[] = {
{"Mercury",King of gods"}}
};
int i = 0;
int sPlanets = sizeof(planets) / sizeof(struct stPlanets);
printf("There are %d planets.\n",planets[i]->planet,planets[i]->deity[0]); //abbreviated to just print first instance.
}
return 0;
}
在第二个例子中,我得到以下内容:
planets-06a.c:11:9: warning: braces around scalar initializer
{"Mercury",^
planets-06a.c:11:9: note: (near initialization for ‘planets[0]’)
planets-06a.c:11:10: warning: initialization of ‘struct stPlanets *’ from incompatible pointer type ‘char *’ [-Wincompatible-pointer-types]
{"Mercury",^~~~~~~~~
planets-06a.c:11:10: note: (near initialization for ‘planets[0]’)
planets-06a.c:11:9: warning: braces around scalar initializer
{"Mercury",
解决方法
在您必须编写的第一个代码片段中
struct stPlanets *pPlanets = planets;
代替
struct stPlanets *pPlanets = &planets;
或者你可以写
struct stPlanets ( *pPlanets )[5] = &planets;
即用作初始化器的数组指示符被隐式转换为指向其第一个元素的指针。
所以在这个声明中
struct stPlanets *pPlanets = planets;
声明的对象和初始化器(隐式转换后)具有相同的类型struct stPlanets *
。
在此声明中
struct stPlanets *pPlanets = &planets;
初始化器的类型为 struct stPlanets ( * )[5]
。所以编译器会发出一条消息,声明的对象和初始化程序的类型不兼容。
在第二个代码片段中这个声明
struct stPlanets *planets[] = {
{"Mercury",{"Messenger"}},{"Venus",{"Love,Beauty"}},{"Earth",{"Earthly things"}},{"Mars",{"War"}},{"Jupiter",{"Sky,Thunder,King of gods"}}
};
不正确,因为您首先需要定义指针数组的元素将指向的结构的对象。
这是您更新的程序。
#include <stdio.h>
int main(void)
{
struct stPlanets {
char *planet;
char *deity[10];
};
struct stPlanets planets[] = {
{"Mercury",King of gods"}}
};
struct stPlanets *pPlanets = planets;
size_t sPlanets = sizeof(planets) / sizeof( *planets );
printf("There are %zu planets.\n",sPlanets);
for ( size_t i = 0; i < sPlanets; i++ )
{
printf("%-10s : %s.\n",pPlanets[i].planet,pPlanets[i].deity[0]);
}
return 0;
}
它的输出是
Mercury : Messenger.
Venus : Love,Beauty.
Earth : Earthly things.
Mars : War.
Jupiter : Sky,King of gods.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。