它被视为全局变量吗?结构和链表

时间:2017-08-27 21:09:55

标签: c struct linked-list global-variables

我搜索过,但找不到我问题的严格答案。 我必须使用动态数据结构编写项目,但我不能使用全局变量。我想使用链表的链表。我在论坛上发现了这段代码(a linked list of linked lists in C),它对我很有用,但我不确定这部分是否被视为全局变量。

typedef struct sToy {
    char name[50];
    struct sToy *next;
}tToy;

typedef struct sChild {
    char name[50];
    tToy *firstToy;
    struct sChild *next;
} tChild;

我指的是“tToy”和“tChild”的事情。 Couse头已经在主要宣布。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

就像@WhozCraig所说,那些是结构类型别名,而不是全局变量。这是一个示例代码,用于说明如何将这些结构用作全局变量或局部变量:

typedef struct sToy {
    char name[50];
    struct sToy *next;
}tToy;

typedef struct sChild {
    char name[50];
    tToy *firstToy;
    struct sChild *next;
} tChild;

tToy Gtoy;//global
tChild Gchild;//global

int main() {
 tToy Ltoy;//local
 tChild Lchild;//local
}

你也可以省略" sToy"和" sChild",只留下" typedef struct {...}别名;"

答案 1 :(得分:0)

您将只需要提供一个局部变量 - 指向头部到子列表的指针以及一些在列表上操作的函数。

这里有两个示例功能 - 一个附加孩子,另一个将玩具附加到孩子的玩具列表中。当然你需要更多它们,但它只是从一开始:

tChild *appendChild(tChild **head, const char *name)
{
     tChild *result = NULL;
     tChild *current = *head;

     while (current != NULL && current ->next != NULL) current = current->next;
     if ((result = malloc(sizeof(tChild))) != NULL)
     {
         if (*head == NULL)
         {
             *head = result;
         }
         else
         {
             current->next = result;
             if (name != NULL) strncpy(result->name, name, sizeof((tChild) {0}.name));
             result->name[sizeof((tChild) { 0 }.name) - 1] = 0; //just in case
             result->firstToy = NULL;
             result->next = NULL;
         }
     }
     return result;
}

tToy *appendToy(tChild *child, const char *name)
{
    tToy *result = NULL;
    tToy *current;

    if (child != NULL)
    {
        current = child->firstToy;
        while (current != NULL && current->next != NULL) current = current->next;
        if ((result = malloc(sizeof(tToy))) != NULL)
        {
            if (child->firstToy == NULL)
            {
                child ->firstToy = result;
            }
            else
            {
                current->next = result;
                if (name != NULL) strncpy(result->name, name, sizeof((tToy) { 0 }.name));
                result->name[sizeof((tToy) { 0 }.name) - 1] = 0; //just in case
                result->next = NULL;
            }
        }
    }
    return result;
}

如何从主

开始
int main(int argc, char **argv)
{

    tChild *head = NULL;

    if (appendChild(&head, "John") == NULL)
        printf("Error - appendingh the child failed\n");
    if (appendChild(&head, "Mark") == NULL)
        printf("Error - appendingh the child failed\n");
.....
相关问题