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

问题描述:

我搜索了,但找不到我的问题严格的答案。 我必须使用动态数据结构编写项目,但我不能使用全局变量。我想使用链表的链表。我在论坛上发现了这个代码(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头已被宣布在主体中。

谢谢你的帮助。

+7

那些开始有型的别名;不是全局变量。 – WhozCraig

+1

这里没有变数。 –

像@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 
} 

你也可以省略了“斯托伊”和“席尔德”,只留下“typedef结构{...}别名;”

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

这里有两个示例函数 - 一个附加子项,另一个附加玩具到孩子的玩具清单。当然,你需要更多的人,但它仅仅是一些从开始:

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"); 
.....