線形リストでスタック #2
'\0'を含めて最大32バイトの文字列をデータに持つ線形リストに修正するパッチ。
--- # # +++ # # @@ -2,10 +2,12 @@ #include <stdlib.h> #include <string.h> +#define NAME_SIZE 32 + typedef struct tagNode Node; struct tagNode { - int data; + char data[NAME_SIZE]; Node *next; }; @@ -15,11 +17,11 @@ typedef struct { CmdType type; - int value; + char value[NAME_SIZE]; } Cmd; void init(Node *head); -void push(Node *head, int data); +void push(Node *head, char *data); void pop(Node *head); void print(Node *head); void get_cmd(Cmd *cmd); @@ -29,10 +31,11 @@ head->next = NULL; } -void push(Node *head, int data) +void push(Node *head, char *data) { Node *n = malloc(sizeof(Node)); - n->data = data; + strncpy(n->data, data, NAME_SIZE); + n->data[NAME_SIZE - 1] = '\0'; n->next = head->next; head->next = n; } @@ -43,7 +46,7 @@ if (n == NULL) { puts("empty list"); } else { - printf("%d\n", n->data); + puts(n->data); head->next = n->next; free(n); } @@ -54,7 +57,7 @@ Node *n; for (n = head->next; n != NULL; n = n->next) { - printf("%d ", n->data); + printf("%s ", n->data); } putchar('\n'); } @@ -75,8 +78,12 @@ } else { s[strlen(s) - 1] = '\0'; if (strncmp(s, "push ", 5) == 0) { - cmd->type = CMD_PUSH; - cmd->value = atoi(s + 5); + if (strlen(s + 5) < NAME_SIZE) { + cmd->type = CMD_PUSH; + strcpy(cmd->value, s + 5); + } else { + cmd->type = CMD_TOOLONG; + } } else if(strcmp(s, "pop") == 0) { cmd->type = CMD_POP; } else if(strcmp(s, "print") == 0) {