簡體   English   中英

C-如何將指針值返回給main?

[英]C - How do I return a pointer value to main?

我有這個作業,要求我使用動態分配創建堆棧並在其中添加一些不同的功能。 現在,通常我會使用頭指針作為全局變量並使事情變得更容易,但是作業要求我將頭指針作為函數的參數,因此我在main中將其設置為局部變量。 這是代碼:

#include <stdio.h>
#include <stdlib.h>

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

void push(int val, node *head) {
    node* temp = (node*) malloc(sizeof(node));
    node* current = head;
    temp->val = val;
    if (head == NULL) {
        head = temp;
        temp->next = NULL;
    }
    else {
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = temp;
        temp->next = NULL;
    }
}

void print(node *head) {
    node* current = head;
    if (current->next != NULL) {
        while (current->next != NULL) {
            printf("%d", current->val);
            current = current->next;
        }
    }
    else {
        printf("%d", current->val);
    }
}

int main() {
    node * head = NULL;
    int n;
    scanf("%d", &n);
    push(n, head);
    print(head);
    push(n, head);
    print(head);
    push(n, head);
    print(head);
}

我在第一個print(head)函數上遇到了一個段錯誤錯誤,說print(head = 0x0) ,這使我相信head在main中返回時不會更新。 我在第一個push函數之后對head使用了printf() ,但我是對的,head返回0 問題是:如何在函數中返回更新的頭部?

您可以像這樣聲明您的函數

void push(int val, node **head)

然后傳遞您的頭部參考並對其進行修改

要么

node *push(int val, node *head)

並返回新的頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM