Dynamic allocation and pointers in Lua

Asked

Viewed 254 times

1

I would like to know how I make dynamic allocation and pointer of a structure in Lua, I have the following instruction 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;
}

1 answer

0


  • No need to pass a pointer copy to the allocation function
    the function aloc() can only return the pointer without receiving anything
  • You forgot to define A and B in function main()
  • Check the result of malloc()
  • Don’t confuse char with char[] (or char*) nor with int
    in the printf() uses "%d" with ints; %c with chars 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 defining the name as a 100 character array you can set as a pointer to char, and then do the malloc() necessary and strcpy().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.