Error in return of a char

Asked

Viewed 82 times

0

I am wanting to make a program that converts a decimal number to binary. By doing this conversion, I wanted to store the decimal numbers in one char. In function is stored right, but when I call the function in the main, is giving problem because I want to equal 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;
}

1 answer

2


You cannot return allocated data within a function since it operates as a stack, when it returns the data is popped and can no longer be accessed (it can even in some cases, but trying to access it is an error). Or you put it on heap, or passes the array raised in the main() by reference and thus the function already uses the actual allocation occurred in the main() to store what you need.

There are other solutions, but for this case it seems the most appropriate.

I initialized the array that could cause problems depending on the content of the memory. I don’t know if the code has other problems.

Put more meaningful names, so comments can be dispensed with. You can simplify it further, 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Behold What are and where are the "stack" and "heap"?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.