Error in returning a char

0

I'm wanting to make a program that converts a decimal number to binary. Doing this conversion, I wanted to store the decimal numbers in char . In the function it is stored right, but when I call the function in main , it is giving problem because I want to match a char to another.

#include <stdio.h>
#include <stdlib.h>    

//n seria o número e qtdade seria a quantidade de bits
char dec2bin(int n, int qtdade) {
// int n; // Número de entrada
 int r; // Resultado do deslocamento
 int i; // Contador

 char operadores[200] = {};

 for(i = qtdade-1; i >= 0; i--) {
    // Executa a operação shift right até a
    // última posição da direita para cada bit.
    r = n >> i;

    // Por meio do "e" lógico ele compara se o valor
    // na posição mais à direita é 1 ou 0
    // e imprime na tela até reproduzir o número binário.
    if(r & 1) {
       // printf("1");
        operadores[qtdade-1-i] = '1';
    } else {
       // printf("0");
        operadores[qtdade-1-i] = '0';
    }
 }

    printf("\n");
    //printf("%s", operadores);
    return operadores;
 //system("pause");
}


int main()
{


    char operadores[200] = {};
    operadores = dec2bin(10, 5);
    printf("\n\n\n\n%s", operadores);

    printf("%s", dec2bin(10,5));
    return 0;
}
    
asked by anonymous 11.04.2017 / 18:17

1 answer

1

You can not return allocated data inside a function since it operates as a stack, when the data is returned it is uncappled and can not be accessed any more (even in some cases, but trying to access it is an error). Either you put it in the heap , or pass the array created in main() by reference and so the function already uses its own allocation in main() to store what it needs .

It has other solutions, but for this case seems the most appropriate.

Initialized the array that could cause problems depending on the contents of the memory. I do not know if the code has other problems.

Put more meaningful names, so comments can be dispensed with. For simplicity, you could have deleted the variable deslocamento , for example.

#include <stdio.h>
#include <stdlib.h>    

void dec2bin(char operadores[], int numero, int qtdadeBits) {
    for (int i = qtdadeBits - 1; i >= 0; i--) {
        int deslocamento = numero >> i;
        operadores[qtdadeBits - 1 - i] = deslocamento & 1 ? '1' : '0';
    }
}

int main() {
    char operadores[200] = { 0 };
    dec2bin(operadores, 10, 5);
    printf("%s", operadores);
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

See What are and where are the stack and heap? .

    
11.04.2017 / 18:33