c - C 中的标签类型

标签 c types stack

<分区>

我目前正在尝试将用户输入的项目推送到 C 中的堆栈(链表结构)中,但我希望能够将各种不同类型的内容输入到堆栈中。现在我的堆栈只能接受 int,但我希望它能够接受其他类型,如 char、double、float 等。

到目前为止我的代码:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>


typedef struct stack
{
    int val;
    struct stack *next;
}node;

node *head = NULL;

void Push (int Item, node **head)
{
    node *New;
    node *get_node(int);
    New = get_node(Item);
    New->next = *head;
    *head = New;
}

node *get_node(int item)
{
    node *temp;
    temp = (node*)malloc(sizeof(node));
    if (temp == NULL) printf("Memory Cannot Be Allocated");
    temp->val = item;
    temp->next = NULL;
    return (temp);
}

int Sempty (node *temp)
{
    if(temp == NULL)
        return 1;
    else
        return 0;
}

int Pop (node **head)
{
    int item;
    node *temp;
    item = (*head)->val;
    temp = *head;
    *head = (*head)->next;
    free(temp);
    return(item);
}

void Display (node **head)
{
    node *temp;
    temp = *head;
    if(Sempty(temp)) printf("The stack is empty\n");
    else
    {
        while (temp != NULL)
        {
            printf("%s", temp->val);
            temp = temp->next;
        }
    }
}

void main()
{
    char* in;
    int data, item, i;
    char length[5];
    for(i = 0; i <= sizeof(length); i++)
    {
    printf("Enter a value: ");
    scanf("%c", &in);
    strcpy(in, in);
    Push(in, &head);
    Display(&head);
    }

}

最佳答案

我会使用 void 指针并在需要时转换它。您不能直接存储它的类型,但您仍然可以使用一个 int 变量来访问将使用正确转换的函数指针数组中的正确函数。

typedef struct stack
{
    void *val;
    int type;
    struct stack *next;
}node;

类型匹配你的函数指针数组的一个函数。 How can I use an array of function pointers?

你也可以在你的“类型”上做一个简单的开关盒(绝对适用)。

编辑: 简单的例子:

while (root != NULL)
    {
        switch (root->type) {
        case 0:
          printf("%d\n", *(int *)(root->val));
          break;
        case 1:
          printf("%c\n", *(char *)(root->val));
          break;
        default:
          printf("unexpected type\n");
        }
        root = root->next;
    }

用 char 而不是 int 可能更有意义,所以你可以只做 case 'c',case 'i'。

小心,你有一个void *,它是一个指向你的变量的指针,不要忘记分配它。

root->val = malloc(sizeof(int));
*(int *)(root->val) = 2;

关于c - C 中的标签类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154323/

相关文章:

c - 为什么 "\r "删除了我之前打印的行,但 "\r"却没有

c - Eclipse(开普勒)不显示结构成员

mysql - MySQL 中的 VARCHAR(255) 和 TINYTEXT 字符串类型有什么区别?

java - 在Java中继承没有父类型的类

c - 释放用 C 实现的堆栈

java - 堆栈被覆盖

c++ - 为什么我在 MinGW 中不需要标志 -lm 但在 Linux 中我明确需要它?

c - c中printf函数的修改

oracle - 如何在 Oracle 数据库中将列的数据类型从 varchar2 更改为数字

stack - 使用内联汇编更改堆栈指针时调用函数会崩溃