如何重新分配参数? [重复]

问题描述 投票:1回答:1

我想知道如何重新分配参数。更具体地说,在test()中,我想重新分配p。当前是一个无效变量。

#include <stdio.h>

#define NULL 0

struct PayloadPtr {
    int prime;
    struct PayloadPtr *next;
};

typedef struct PayloadPtr *Payload;

Payload new_payload(int prime, Payload next) {
    Payload p = (Payload) malloc(sizeof(struct PayloadPtr));
    p->prime = prime;
    p->next = next;
    return p;
}

void test(Payload p, int n) {
    if (p->prime * (n / p->prime) == n) {

    } else if (p->next == NULL) {
        printf("%d\n", n);

        // HERE! p is a dead variable, how to re-assign the argument?
        p = new_payload(n, p);
    } else {
        test(p->next, n);
    }
}

int main() {
    Payload p = new_payload(2, NULL);

    printf("%d\n", 2);

    int i;
    for (i = 2; i < 11; i++) {
        test(p, i);
    }

    return 0;
}
c
1个回答
0
投票
void test(Payload *p, int n) {
    if ((*p)->prime * (n / (*p)->prime) == n) {

    } else if ((*p)->next == NULL) {
        printf("%d\n", n);

         *p = new_payload(n, *p);
    } else {
        test(&((*p)->next), n);
    }
}

int main() {
    Payload pHead = new_payload(2, NULL);

    printf("%d\n", 2);

    int i;
    for (i = 2; i < 11; i++) {
        test(&pHead, i);
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.