【问题标题】:My C code tracing and output is different but I am not sure why?我的 C 代码跟踪和输出不同,但我不知道为什么?
【发布时间】:2019-05-12 20:20:12
【问题描述】:

我正在跟踪我的教授给出的链表 C 代码,但我不确定它是如何工作的。第一部分最让我困惑。我以为 head 是 4,因为 temp 是 0,所以 head+temp 是 4。但是,ptr 是 5 而不是 4。谁能解释发生了什么? 除了代码之外,我将实际输出放在 cmets 中。

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int info;
    struct node *next;
};
typedef struct node node;
int func1 (node *head)
{
    int temp = 0;
    while (head !=NULL) 
    {
        temp = temp + head -> info;
        head = head->next;
    }
    return(temp);
}
int main() 
{
    node *ptr,*ptr2,*ptr3; //ptr ptr2 ptr3 

    ptr = (node*)malloc(sizeof(node));
    ptr->info = 4;//what is this??
    ptr2 = (node*)malloc(sizeof(node));
    ptr->next = ptr2;
    ptr2->next = NULL;
    ptr->next->info = 1;//5 1 <-actual list //what happened to 4?? 

    printf("ptr2 %d\n",func1(ptr2));//1 
    printf("ptr %d\n",func1(ptr));//5 

    ptr3 = (node*)malloc(sizeof(node));//5 1 _ 
    ptr3->next = ptr;//5 1 _ ? //but there's no space for ptr3->next??

    ptr3->info = 2;//5 1 7 <-actual list
    printf("ptr3 %d\n",func1(ptr3));//7 

    ptr2->info = 8;//12 8 14 <-actual list
    printf("ptr3 %d\n",func1(ptr3));//14 

    ptr->info = 16;//24 8 26 <-actual list
    printf("ptr2 %d\n",func1(ptr));//24     
}

【问题讨论】:

    标签: function loops linked-list nodes trace


    【解决方案1】:

    添加了 cmets,但对我来说似乎有意义?

    ptr = (node*)malloc(sizeof(node));
    ptr->info = 4;//what is this??
    

    // 4 是你放入这个节点的值

    ptr2 = (node*)malloc(sizeof(node));
    ptr->next = ptr2;
    ptr2->next = NULL;
    

    // ptr 是链表中的第一个元素,ptr2 现在是第二个

    ptr->next->info = 1;//5 1 <-actual list //what happened to 4?? 
    

    //给ptr->next赋值,即ptr2-4原封不动地留在第一个节点

    printf("ptr2 %d\n",func1(ptr2));//1 
    

    // 1 有意义,因为 ptr2 是链表中的最后一个元素

    printf("ptr %d\n",func1(ptr));//5 
    

    // 5 有意义,因为 ptr 是第一个元素

    ptr3 = (node*)malloc(sizeof(node));//5 1 _ 
    ptr3->next = ptr;//5 1 _ ? //but there's no space for ptr3->next??
    

    // 没有空格? // ptr3 现在是链表中的第一个元素

    HTH!

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2014-01-17
      • 2021-10-07
      • 2017-04-01
      • 2013-03-20
      相关资源
      最近更新 更多