结构化类型数组初始化

时间:2016-11-27 23:20:01

标签: c arrays struct

我有结构,我有这个结构化类型数组,我试图初始化数组元素使用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 任何人都可以弄明白并解释我,我做错了什么。

1 个答案:

答案 0 :(得分:0)

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(;;);来暂停程序的调试模式。