Dynamic Allocation and Pointers on the Moon

1

I would like to know how to do dynamic allocation and pointer of a structure in Lua, I have the following statement in C that I need to pass to Lua;

typedef struct ilha {
    char name;
    struct ilha *prox1, *prox2, *prox3;
} *Ilha;

Ilha aloc(Ilha x) {
    x = malloc(sizeof(struct ilha));
    return x;
}

int main() {
    A = aloc(A);
    B = aloc(B);
    B->name = "Hello Word";
    A->prox1 = B;
    printf("%d", A->prox1->name);
    return 0;
}
    
asked by anonymous 10.11.2015 / 14:08

1 answer

0
  • You do not need to pass a copy of the pointer to the allocation function
    the function aloc() can only return the pointer without receiving anything
  • You forgot to set A and B in function main()
  • Checks the result of malloc()
  • Do not confuse char with char[] (or char* ) nor int
    no printf() uses "%d" with int s; %c with char s and %s with strings ( char[] or char* )

After looking at these points, I changed your program to:

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

struct ilha {
    char name[100];
    struct ilha *prox1, *prox2, *prox3;
};

struct ilha *aloc(void) {
    struct ilha *x = malloc(sizeof *x);
    return x;
}

int main() {
    struct ilha *A = aloc();
    if (A == NULL) exit(1);
    struct ilha *B = aloc();
    if (B == NULL) exit(2);
    strcpy(B->name, "Hello Word");
    A->prox1 = B;
    printf("%s\n", A->prox1->name);

    return 0;
}

Instead of setting name to an array of 100 characters you can set it as a pointer to char, and then make malloc() required and strcpy() .

    
10.11.2015 / 15:25