C - Cannot start a pointer that is passed as an argument

#include <stdio.h>
#include <stdlib.h>
typedef struct {
    unsigned length;
} List;
void init(List *l) {
    l = (List *) malloc(sizeof(List));
    l->length = 3;
}
int main(void) {
    List *list = NULL;
    init(list);
    if(list != NULL) {
        printf("length final %d \n", list->length);
        return 0;
    }
    return 1;
}

This is a simplified version of the code that gives me problems. I am trying to build a pointer *listfrom a method in which *listis passed as a parameter.

I know that I can do the work void init(List *l)by changing it to void init(List **l), but this is for the class textbook. I cannot change the arguments of a method. I spent four hours on this.

I want to make sure that there is no way to do the work void init(List *l)before I run into my professor.

Thanks in advance

+5
source share
4 answers

init, , , init. . , , , .

void init(List **l) {
    *l = (List *) malloc(sizeof(List));
    (*l)->length = 3;
}

init(&list);

, List init? , List length = 3 - - :

void init(List *l) {
  l->length = 3;
}

List list;
init(&list);
printf("length final %d \n", list.length);
+4

, , . , . :

void init(List** l) {
   *l = (List*) malloc(sizeof(List));
   // ...
}

, init(list) init(&list). , , :

List* init() {
    List* result = (List *) malloc(sizeof(List));
    result->length = 3;
    return result;
}

, , list = init();.

, ++ , . , , .

, , init() , . , init(), , . .

+3

, , . , .

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
    unsigned length;
} List;


void init(List *l) {
    l->length = 3;
}
int main(void) {
    List list;// x = NULL;
    memset(&list,0,sizeof(List));
    init(&list);
    printf("length final %d \n", list.length);
    return 1;
}

List, List. init() init, .

./a.out

final 3

+1

init . , . -, , , . , , , init malloc . , , , , - , , , .

0

All Articles