typedef struct Tag_Person
{
char name[10];
int tall;
int age;
}Person;
//每个初始化元素实际是一个变量,会占用芯片ram资源
//这样编译能过【有警告】,但运行时无法正常获取第2及和后面的元素
//原因是右边是一个结构体实体的内容而非指针。
//Person *psnx={"Jhon",188,22};
Person *psn0=&(Person){"Jackey",175,23};
Person *psn1[4]=
{
&(Person){"Tom",160,14},
&(Person){"Marry",175,18},
&(Person){"Terry",155,20},
&(Person){"Suson",168,15}
};
//不占用芯片ram资源,初始化数据变成常量code
Person *psn2[4]=
{
(Person *)&(const Person){"Tom",160,14},
(Person *)&(const Person){"Marry",175,18},
(Person *)&(const Person){"Terry",155,20},
(Person *)&(const Person){"Suson",168,15}
};
void main()
{
printf("===Check build time:[%s]====\r\n",__TIME__);
printf("#Name=%s,tall=%d,age=%d.\n",psn0->name,psn0->tall,psn0->age);
psn0= &(Person){"Bill",180,35}; //接受重新赋值,或用此方式初始化!
printf("$Name=%s,tall=%d,age=%d.\n",psn0->name,psn0->tall,psn0->age);
for(int i=0;i<4;i++)
{
printf("_Name=%s,tall=%d,age=%d.\n",psn1[i]->name,psn1[i]->tall,psn1[i]->age);
psn1[i]->age+=100;//可以修改
}
for(int i=0;i<4;i++)
{
printf("-Name=%s,tall=%d,age=%d.\n",psn2[i]->name,psn2[i]->tall,psn2[i]->age);
psn2[i]->age+=100;//修改会导致运行出错!
}
}
[C语言] 结构体指针的初始化
于 2023-08-09 15:39:11 首次发布