How to allocate dynamically when I do not know how many positions I will use in C?

10

In a part of the code I need to transform an integer into binary and store it in a vector of characters, however, I do not know which integer I'm going to get to binary, so I do not know how many positions my vector will have %.

How to handle this problem with dynamic allocation? I need to allocate spaces in memory according to the need of my program, since I will receive a char and I need to transform this int to binary, however, I do not know the values.     

asked by anonymous 31.08.2015 / 02:56

2 answers

6

A int will (almost) always be 32 bits, so you know the size required. Even if you do not know, in such cases it is best to allocate enough to the greatest possible. It's actually something so simple you should not allocate dynamically. Make the allocation as the vector and do not worry about it.

As the comments I made a code to at least demonstrate the operation (as missing information in the question, it will need adaptations):

#include <stdio.h>

int main(void) {
    int inteiro = 3;
    int tamanho = sizeof(int) * 8; //aqui acha o tamanho de um int
    char binario[tamanho + 1]; //aqui aloca o vetor de char com espaço para o terminador
    int i = tamanho - 1; //inicia o contador
    while(i > 0) {
        binario[i] = inteiro % 2 + 48; //acha o binário
        inteiro /= 2;
        i--;
    }
    binario[tamanho] = '
#include <stdio.h>

int main(void) {
    int inteiro = 3;
    int tamanho = sizeof(int) * 8; //aqui acha o tamanho de um int
    char binario[tamanho + 1]; //aqui aloca o vetor de char com espaço para o terminador
    int i = tamanho - 1; //inicia o contador
    while(i > 0) {
        binario[i] = inteiro % 2 + 48; //acha o binário
        inteiro /= 2;
        i--;
    }
    binario[tamanho] = '%pre%'; //coloca o terminador
    printf("%s", binario);
    return 0;
}
'; //coloca o terminador printf("%s", binario); return 0; }

See running on ideone .

Please note that it does not consider the endianness .

    
31.08.2015 / 03:01
0

The @bigown solution would solve.

But I leave mine too.

Starting from the beginning where sizeof(int) - > returns the number of bytes an integer type uses in memory, in this case it would return 4, then multiply by 8 for terms in bits, and thus the result would be 32 .

int tamanho = sizeof(int)*8;//sizeof de int para independer da arquitetura 
 char vetor[tamanho];

For "unnecessary" zeros, making a way to remove them would be time-consuming, and if it were to save space, that would be unnecessary.

    
31.08.2015 / 05:14