gpt4 book ai didi

c - 结构化类型数组初始化

转载 作者:行者123 更新时间:2023-11-30 16:53:31 25 4
gpt4 key购买 nike

我有结构,并且有这个结构化类型数组,我正在尝试使用 for 初始化数组元素,但字符串数组是相同的

#include "stdafx.h"
#include "string.h"

#define NUMBER_OF_STARS 200
#define NUMBER_OF_PLANETS 200

//== STAR STRUCTURE ==//
// NAME | DIAMTER | TEMPERATURE | COMPANION PLANET/S //
//== END STRUCTURE ==//
typedef struct _star
{
char *name;
int diameter;
int temperature;

}star;
//== STAR STRUCTURE ==//
// NAME | DISTANCE TO STAR | TWIRLING STAR | SPEED IN SPACE //
//== END STRUCTURE ==//
typedef struct _planet
{
char *name;
int distance_to_star;
char *twirling_star;
int speed_in_space;
}planet;
typedef struct _galaxy
{
star s_star;
planet s_planet;
}galaxy;

int main()
{
star s_star[NUMBER_OF_STARS];
printf("Create your STARS\n");
for (int i = 0; i < 200; ++i)
{
printf("Enter name of STAR\n");
char s_name[20];
scanf_s(" %s", s_name, 20);
printf("Enter diameter of STAR\n");
int s_diameter;
scanf_s(" %i", &s_diameter);
printf("Enter temperature of STAR\n");
int s_temperature;
scanf_s("%i", &s_temperature);
char s_com_planet[20];
printf("\n");
s_star[i] = { s_name,s_diameter,s_temperature };
printf("Would you want to create another one?(YES/NO)\n");
char cmd_answer[5];
scanf_s("%s", cmd_answer, 5);
if (strstr(cmd_answer, "YES")) continue;
else if(strstr(cmd_answer, "NO")) break;
else break;
//printf("Name of STAR:\t\t%s\nDiameter of STAR:\t%i\nTemperature of STAR:\t%i\n\n", s_star->name, s_star->diameter, s_star->temperature);
}

printf("%s", s_star[1].name);

for (;;);
return 0;
}

当我输入时:

 name1 
1
1

再一次

name2
2
2

然后再说

name3
3
3

Visual Studio 显示在 s_star 数组中 s_star[0].name s_star[1].name s_star[2 ].name 在我的例子中是相同的,输出是 name3谁能弄清楚这一点并解释我,我做错了什么。

最佳答案

star 包含指针。您可以将数组初始化为零,如下所示:

star s_star[NUMBER_OF_STARS] = { 0 };

如果star不包含指针,您可以在声明期间初始化:

star s = { 0,123,456 };
//or
star array[] = { {1,2,3}, {4,5,6} };

但在这种情况下,您必须手动设置成员:

//(in this case is not necessary to check the previous value)
if (s_star[i].name)
free(s_star[i].name);

s_star[i].name = malloc(strlen(s_name) + 1);
strcpy_s(s_star[i].name, (strlen(s_name) + 1), s_name);

s_star[i].diameter = s_diameter;
s_star[i].temperature = s_temperature;

与您的问题无关,但在 Visual Studio 中使用 system("pause") 而不是 for(;;); 在 Debug模式下暂停程序。

关于c - 结构化类型数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com