3
Why this program that divides a number into decimal notation, transforms it into binary notation and prints the number on the screen in the correct sequence (from bit most significant for the least significant) uses malloc
twice?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
// Stack
int decimal, q, r;
int counter, i;
char *binary = NULL;
char *aux;
printf("Digite um número em base decimal: ");
scanf("%d", &decimal);
counter = 1;
while (decimal >= 2) {
q = decimal / 2;
r = decimal - (q * 2);
// Heap
aux = (char *) malloc(counter * sizeof(char));
if (binary != NULL) {
memcpy(aux, binary, counter-1);
free(binary);
}
binary = aux;
if (r == 0) {
binary[counter-1] = 48; //'0';
} else {
binary[counter-1] = 49; //'1';
}
//printf("resto %d = %d\n", counter, r);
counter++;
decimal = q;
}
//printf("ultimo quociente = %d\n", q);
// Heap
aux = (char *) malloc(counter * sizeof(char));
if (binary != NULL) {
memcpy(aux, binary, counter-1);
free(binary);
}
binary = aux;
if (decimal == 0) {
binary[counter-1] = 48; //'0';
} else {
binary[counter-1] = 49; //'1';
}
printf("Resultado em binário = ");
for (i = counter-1; i >= 0; i--) {
printf("%c", binary[i]);
}
printf("\n");
free(binary);
return 0;
}
I haven’t looked deeply but is there any reason to allocate dynamic memory? Actually the algorithm is very confusing. You probably don’t need to do so much. Did you? Do you have any requirement to do so?
– Maniero
It’s a code that my teacher asked me to analyze and I’m doubtful about that part, the idea was to use all this code to research about everything
– Gabriel Vinicius
Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?
– Maniero