I tried to allocate memory to my struct but it didn't work. Here is the piece of my programme where it goes wrong (also the declaration of the structs).
struct ptr {
int tel;
char nome;
struct ptr *prox;
};
struct reg{
char letra;
struct ptr *inicio;
};
struct reg agenda[26];
agenda[l].inicio = (struct ptr*)malloc(sizeof(struct ptr));
agenda[l].inicio->prox = (struct ptr*)NULL;
strcpy(agenda[l].inicio->nome,nome);
Try changing the nome char to a char pointer. Also before strcpy you have to allocate memory for the pointer.
struct ptr {
int tel;
char *nome;
struct ptr *prox;
};
struct reg{
char letra;
struct ptr *inicio;
};
struct reg agenda[26];
agenda[l].inicio = (struct ptr*)malloc(sizeof(struct ptr));
agenda[l].inicio->prox = (struct ptr*)NULL;
agenda[l].inicio->nome = (char*)malloc(MAX_NOME_LENGTH);
strcpy(agenda[l].inicio->nome,nome);
Of course change MAX_NOME_LENGTH
to the maximum size of the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.