C中的通用链表出现问题 [英] Generic linked list in C got problem

查看:71
本文介绍了C中的通用链表出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>


struct node{
    void* n;
    struct node*next;
};



struct node* head = NULL;

struct node* push(void* a, int size){

    if (head == NULL){
    
        head = (struct node*)malloc(sizeof(struct node));
        head->n = malloc(size);
        memcpy(head->n, a, size);
        head->next = NULL;
    }
    else{
    
        temp = (struct node*)malloc(sizeof(struct node));
        temp->n = malloc(size);
        memcpy(temp->n, a, size);
        temp->next = head;
        head = temp;
    }
    return head;
}


int main()
{
    struct node* temp;
    int n = 1;
    char ch;
    
    
    temp = push(&n, 4);
    
    while (temp != NULL)
    {
        printf("%d",temp->n);
        temp = temp->next;
    }
    
    temp = push('c', 1);
    
    while (temp != NULL)
    {   
        printf("%d", temp->n);
        temp = temp->next;
    }  
}







这里我要实现一个链表和输出c中的链表。但是当我编译它时,我得到了一些垃圾值。



我尝试过:



我试图实现通用的c链表。但输出结果是垃圾值。问题是什么?




Here I want to implement a linked list and output the linked list in c.But when i compile it I got some garbage value.

What I have tried:

I tried to implement generic c linked list.But the out put came out as a garbage value. Whats the problem?

推荐答案

你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



这段代码很奇怪

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

This code is weird
head=(struct node*)malloc(sizeof(struct node));
head->n=malloc(size);



当你重读它时,你怎么知道 head-> n 的大小? / strike>

你应该读这个!

C void指针 - C编程 - c4learn.com [ ^ ]

取消引用空指针在C编程 - c4learn.com [ ^ ]

我认为你需要有一个很好的理由来使用这个结构。


How can you know the size of head->n when you reread it ?

You should read this!
C void pointers - C Programming - c4learn.com[^]
Dereferencing Void Pointer in C Programming - c4learn.com[^]
I think you need to have a really good reason to use this construct.


这篇关于C中的通用链表出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆