I'm trying to make a program that calculates the probability of a given caracter goes after a certain sequence of caracters. To do so i'm using a struct node, as implemented bellow:
typedef struct node
{
struct node* prox[nchars];
int* ocorrencias;
int n;
} node;
The n refers to the number of times the specific node apeared. The pointer "ocorrencias" is actually an array that has nchars size, and each entry represents the number of times a given caracter has appeared after the current node. To initialize each node i use the following function:
void AlocaNode(node* qualquer){
//Função usada para inicializar as variaveis de um node
qualquer = malloc(sizeof(node));
qualquer->n = 0;
qualquer->ocorrencias = (int *)calloc(nchars, sizeof(int));
}
My problem is when i try to change the values of the node. I must have tried a duzen of different algoritms to update the ocorrencias array. The last one i tried is written bellow. pos is an intenger, and i'm sure it has a valid value.
//Pegamos a posição do caracter no array
pos = retornaPos(letra);
//Atualizamos a ocorrencias no node
int *prt = malloc(sizeof(int));
prt = &atual->ocorrencias;
*(prt+pos) = *(prt+pos) + 1;
//E o número de vezes que o node apareceu
atual->n++;
//Verificamos se o node atual já foi alocado
if (atual->prox[pos] == NULL){
AlocaNode(atual->prox[pos]);
}
//E atualizamos o nosso node para apontar para o próximo
atual = atual->prox[pos];
What am i doing wrong? How do i update its value?
Your AlocaNode
loses the memory allocated, because the variable qualquer
goes out of scope after the function exits:
void AlocaNode(node* qualquer) {
qualquer = malloc(sizeof(node));
qualquer->n = 0;
qualquer->ocorrencias = (int *)calloc(nchars, sizeof(int));
}
The node from the calling function isn't updated. Instead, you could pass a double pointer to node:
void AlocaNode(node **qualquer) {
*qualquer = malloc(sizeof(node));
(*qualquer)->n = 0;
(*qualquer)->ocorrencias = calloc(nchars, sizeof(int));
}
and call like this:
node qualquer;
AlocaNode(&qualquer);
Another possibility is to return the new node from the function:
node *AlocaNode(void) {
node *qualquer = malloc(sizeof(node));
(*qualquer)->n = 0;
(*qualquer)->ocorrencias = calloc(nchars, sizeof(int));
return qualquer;
}
and call like this:
node qualquer = AlocaNode();
(I prefer the second variant.)
int *prt = malloc(sizeof(int));
prt = &atual->ocorrencias;
Memory leak, you reserve space for prt
but this address is replaced on the next line, furthermore atual->ocorrencias
is already a pointer (don't use the address-of operator &
)
Change to:
int *prt = atual->ocorrencias;
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.