TOPIC

runtime error

lfrsousa asked 4 years ago

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

typedef struct{
    char palavra[50];
    int tamanho;
}Tpalavra;

void insertionSort (Tpalavra *v, int n) {
int i, j;
Tpalavra aux;
for (i = 1; i < n; i++) {
 aux = v[i];
 j = i - 1;
 while (j >= 0 && aux.tamanho > v[j].tamanho) {
 v[j+1] = v[j];
 j--;
 }
 v[j+1] = aux;
}
}
void func2(Tpalavra *v,char *palavra,int quantidade ){
        int k;

        for(k=0;k<quantidade;k++){
            if (k==0){
                strcat(palavra,v[k].palavra);
            }else{
            strcat(palavra," ");
            strcat(palavra,v[k].palavra);
        }
    }}

int main(){
    int i,j,quantidade,N_elementos,tamanho;
    char **strings;
    Tpalavra *lista;

    tamanho=0;
    N_elementos=0;

    printf("quantidade de palavras: ");
    scanf("%d",&quantidade);

    strings = malloc(sizeof(char*)*quantidade);
    for (i=0;i<=quantidade;i++){
        strings[i] = malloc(sizeof(char) * 50);
        //memset(strings[i],0,sizeof(char)*50);
    }

    lista=(Tpalavra*)malloc(sizeof(Tpalavra)*50);

    //memset(lista[N_elementos].palavra,0,sizeof(char)*50);

    for(j=0;j<quantidade;j++){
        scanf(" %[^\n]s", strings[j]);
        lista[N_elementos].tamanho=0;

        for(i=0;i<=strlen(strings[j]);i++){
            if(strings[j][i] == ' '){
                N_elementos +=1;
                tamanho=0;

            }else if(strings[j][i]=='\0'){
                N_elementos +=1;
                insertionSort(lista,N_elementos);
                memset(strings[j],0,sizeof(char)*50);
                func2(lista,strings[j],N_elementos);
                memset(lista,0,sizeof(Tpalavra)*50);
                N_elementos = 0;
                tamanho = 0;
            }else{
                lista[N_elementos].palavra[tamanho]=strings[j][i];
                tamanho+=1;
                lista[N_elementos].tamanho += 1;
            }
        }
    }
    for(j=0;j<quantidade;j++){
        printf("%s\n",strings[j]);
    }
}

está dando runtime error! mas está funcionando!

Remember not post solutions. Your post may be reviewed by our moderators.

  • feodorv replied 4 years ago

        char palavra[50];
        strings[i] = malloc(sizeof(char) * 50);

    Why to be so greedy??? Why not

        char palavra[56];
        strings[i] = malloc(sizeof(char) * 56);

    Or

        char palavra[52];
        strings[i] = malloc(sizeof(char) * 52);

    at the last end??? The problem states that

    each of the strings of the set may contain between 1 and 50 inclusive characters

    And +1 we need for '\0' at the very end of a symbol list as a mark of string's end.