c - 在双向链表中正确分配结构指针

标签 c pointers linked-list

我做了一个简单的双链表;该程序运行良好,但我收到了一些编译器警告,我需要删除这些警告。警告是:从不兼容的指针类型赋值 [默认启用]。它们位于标有///(警告)的位置。为简单起见,程序被删节了:

struct stack_struct
{
int data;
struct stack *next;
struct stack *previous;
};

typedef struct stack_struct *Stack_struct;
/// -------------------------------------------------------------------------------
void push(Stack_struct *stack, int Data);
void print_stack(Stack_struct stack);
void pop(Stack_struct *stack);
/// -------------------------------------------------------------------------------
int main()
{
Stack_struct stack = NULL;

...Print instructions...
...gets answer...

if(answer == LIST)
    print_stack(stack);

else if(answer == REMOVE)
    {
    if(stack == NULL)
        ...print message...
    else
        pop(&stack);
    }
else
    push(&stack, answer, &answer_type);

return 0;
}
/// -------------------------------------------------------------------------------
void push(Stack_struct *Stack, int Data)
{
Stack_struct new_node = malloc(sizeof(struct stack_struct));

new_node->data = Data;

 if(*Stack == NULL)
    {
    new_node->next = new_node->previous = NULL;
    *Stack = new_node;
    }
 else
    {
    new_node->next = *Stack; ///(WARNING)
    (*Stack)->previous = new_node; ///(WARNING)
    new_node->previous = NULL;
    *Stack = new_node;
    }
}
/// -------------------------------------------------------------------------------
void print_stack(Stack_struct Stack)
{
Stack_struct temp_node = Stack;

while(temp_node)
    {
    printf("%d ", temp_node->data);
    temp_node = temp_node->next; ///(WARNING)
    }
}
/// -------------------------------------------------------------------------------
void pop(Stack_struct *Stack)
{
Stack_struct delete_node = *Stack;
*Stack = (*Stack)->next; ///(WARNING)
free(delete_node);
}

最佳答案

您的结构类型显示为:

struct stack_struct
{
    int data;
    struct stack *next;
};

请注意,next 是指向 struct stack 的指针,而不是 struct stack_struct,因此它是指向不同类型的指针。您可以像这样引入一个类型,例如 struct stack;如果它不是已知类型,则只能使用指向该类型的指针,直到该类型被完全定义 — 但请参阅 Which part of the C standard allows this code to compile?了解更多信息。但是,在这种情况下很明显您不打算引用不同的类型。

解决这个问题,很多问题都会消失。

我注意到代码引用了结构的 previous 成员;这对于双向链表来说是正常的,但是在将问题添加到 SO 之前进行修剪时你有点过于热情了。 因此,你的结构类型应该是:

struct stack_struct
{
    int data;
    struct stack_struct *next;
    struct stack_struct *previous;  // Often abbreviated to prev
};

关于c - 在双向链表中正确分配结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21395170/

相关文章:

c++ - 并发使用中内联汇编的设计元素

c - 函数层次和C指针初始化问题

我可以在 C 中搜索字符串中的字符 (X OR Y) 吗?

c++ - Cout 不打印号码

c++ - 指针 vector : some clarification needed

c# - C#中链表的大小

c++ - cout 和 printf 在显示链表时显示不同的结果

c - 将行读入单链表的最佳方法

c - LD:将共享库链接到静态库

c - 将大量逻辑打包在单个 C 语句中有何优点和缺点?