- 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()
.