0

I am wondering how to reassign a parameter. More specifically, in test() I want to reassign p. It is currently a dead variable.

#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;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • 1
    You *have* reassigned it with `p = new_payload(n, p);` but the new value is unused. Do you mean how to pass the new value back to the caller? – Weather Vane Mar 05 '20 at 17:05

1 Answers1

1
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;
}
Landstalker
  • 1,368
  • 8
  • 9