【问题标题】:How do I access my struct's elements in different if statements?如何在不同的 if 语句中访问结构的元素?
【发布时间】:2018-05-18 00:13:18
【问题描述】:

抱歉,如果这是一个非常愚蠢的问题。

我已经在此处声明并初始化了一个结构数组(就在 for 循环上方);

printf("\n>>>");
    scanf( "%s" , &CurrentCommand);

    if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();
        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        struct StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

        for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;

            Plot(r1, r2, '.');
        }

    }

我已经在第一个 IF 语句的 for 循环中访问了我需要的元素,但是我不再能够在我的第二个 IF 循环中访问它们,可能是因为“struct StarsStruct *Stars”是在本地声明的。

那么我怎样才能在另一个 if 语句中访问它呢?一开始就声明它是行不通的,因为我猜想用 malloc 创建数组必须一次性完成,包括声明和初始化。

总而言之,我想访问 Stars 结构的成员,在我将创建的另一个 IF 语句中,Stars[1].SerialNumber 等。但是我目前不能。

【问题讨论】:

  • 您仍然可以在更高范围内的某处定义变量,但在其他地方初始化它。

标签: c arrays struct initialization declaration


【解决方案1】:

您需要在需要的地方进一步定义变量。您只需要将其初始化为NULL,然后您可以稍后将malloc 的结果分配到您需要的位置。

// define up here and initialize to NULL
struct StarsStruct *Stars = NULL;

printf("\n>>>");
scanf( "%s" , &CurrentCommand);

if (strcmp(CurrentCommand, "bang") == 0)
{
    Clear();
    printf("Enter the number of stars to be created: ");
    scanf("%d", &NumberOfStars);

    // assign here
    Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

    for (int i = 0; i < NumberOfStars; i++)
    {
        r1 = rand() % (60 + 1 - 0) + 0;
        r2 = rand() % (30 + 1 - 0) + 0;

        Stars[i].SerialNumber = i;
        Stars[i].x = r1;
        Stars[i].y = r2;

        Plot(r1, r2, '.');
    }

}

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 2017-04-28
    • 2022-08-19
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2021-12-27
    • 2021-08-11
    相关资源
    最近更新 更多