Casting of malloc return in string matrix

Asked

Viewed 14 times

1

The objective of the program is to inform the number of days, hours, minutes and seconds corresponding to the number of seconds in the input. If the value is less than zero, the output should be zero to the left of the digit.

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

int qtdDigitos(int n){
    int qtdDigitos = 0;
    if(n==0)
        return qtdDigitos;
    else
        while (n != 0){
            qtdDigitos++;
            n/=10;
        }
    return qtdDigitos;
}
char *converteString(int n){
    int qDigitos = qtdDigitos(n);
    char *str = (char *)malloc(sizeof(char)*(qDigitos+1));
    int m;
    char c;
    for (int i = (qDigitos-1); i >= 0; i--){
        if(n>=10){
            m = n%10;
            n/=10;
        }
        else if(n<10)
            m = n;
        c = m+'0';
        str[i] = c;

    }
    c = n+'0';
    str[0] = c;
    str[qDigitos]= '\0';
    return str;
}

int main(){
    int dadosInteiros[4], segundos;
    char **dadosString = (char **)malloc(4 * sizeof(char*));
    int ret = scanf("%d", &segundos);
    if(ret!=1 || segundos<0)
        printf("ERRO\n");
    else{
        dadosInteiros[0] = segundos/86400;
        segundos %= 86400;
        dadosInteiros[1] = segundos/3600;
        segundos %= 3600;
        dadosInteiros[2] = segundos/60;
        segundos %= 60;
        dadosInteiros[3] = segundos;
        for (int i = 0; i < 4; i++){
            if(dadosInteiros[i]>=10){
                dadosString[i] = (char*)malloc(sizeof(char)*(qtdDigitos(dadosInteiros[i])+1));
                strcpy(dadosString[i], converteString(dadosInteiros[i]));
            }   
            else{
                dadosString[i] = (char*)malloc(sizeof(char)*3);
                char c = dadosInteiros[i] + '0';
                dadosString[i][1] = c;
                dadosString[i][0] = '0';
                dadosString[i][2] = '\0';
            }
            
        }
        
        printf("%sd%sh%sm%ss\n", dadosString[0], dadosString[1], dadosString[2], dadosString[3]);
    }
    

    return 0;
}


The program is working as expected, but I’m doubtful if the casting at the return of malloc on lines 2 and 16 of main is correct. In the first, I allocate a pointer vector of the type char and in the second I fill each of the positions with a string.

  • Read also https://answall.com/search?q=%5Bc%5D+sizeof+char+%22sempre+1%22

No answers

Browser other questions tagged

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