Trash value in a C array

Asked

Viewed 24 times

0

I am making a program whose function is to import the values of a file . dat and put them inside a vector. For this, I made the following code:

void Import_vec(int tamanho,const char caminho[],float * vetor,int chave)
{

    FILE *arquivo = fopen(caminho,"r");

    for(int i = 0;i<tamanho;i++)
    {
        fscanf(arquivo, "%f\t", &vetor[i]);
        if(chave == 1)
        {
            printf("%f\n",vetor[i]); // Caso seja 1, os valores serão impressos no terminal
        }
    }
    fclose(arquivo);
}

In the output appear all the correct values, but when finished printing the last value appears a Trash value (gigantic value that is not in the file).

Output:

    0.918033
    -0.981341
    0.241689
    2.344740
    -1.605030
    -1.395590
    -1.280210
    1.801470
    -0.216157
    -1.634040
    23.3161324.0574250.878794-6.604258-8.68799711.96468212.795636-5.3303821.332010-8.0112750.7523827.292252-11.467504-0.8759   
2310.2975292.430890-13.0802069.1249843.690364-16.438658

Before using fscanf() I used fgets(), strtok and strtod to read the line, separate the values based on a token and convert the string to a float, but still gave the same problem. What could it be? What causes this? How can I avoid it? Another problem: the size of the vector is 10, but with Trash value the vector ends up having 11 values. How? (To allocate the vector I used malloc(10*sizeof(float))). If you need additional information, the complete code is:

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

float *Alloc_vec(int n){
    float *v = malloc(n*sizeof(float));
    if(v == NULL)
    {
        exit(EXIT_FAILURE);
    }
    return v;
}


float **Alloc_array(int n, int m){
    float **matriz;
    matriz = malloc(n*sizeof(float *));
    if(matriz == NULL)
    {
        exit(EXIT_FAILURE);
    }
    for(int i = 0;i<n;i++){
        matriz[i] = malloc(m*sizeof(float ));
        if(matriz[i] == NULL){
            exit(EXIT_FAILURE);
        }
    }
    return matriz;
}


void Import_vec(int tamanho,const char caminho[],float * vetor,int chave)
{

    FILE *arquivo = fopen(caminho,"r");

    for(int i = 0;i<tamanho;i++)
    {
        fscanf(arquivo, "%f\t", &vetor[i]);
        if(vetor[i] >10)
        {
            vetor[i] = 0;
        }
        sleep(1);
        if(chave == 1)
        {
            printf("%f\n",vetor[i]);
        }
    }
    fclose(arquivo);
}


void Import_array(int n, int m ,const char caminho[],float ** matriz,int chave)
{
    FILE *arquivo = fopen(caminho,"r");
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            fscanf(arquivo, "%f ", &matriz[i][j]);
            if(chave == 1)
            {
                printf("%f ",matriz[i][j]);
            }
        }

    }
    fclose(arquivo);

}

int main(){
    int Ni=20,Nj=30,Nk=10;
    float *u = Alloc_vec(Nk);
    float *v = Alloc_vec(Nj);
    float **A = Alloc_array(Ni,Nk);
    float **B = Alloc_array(Nk,Nj);
    char caminho_u[] = "u_vec.dat";
    char caminho_v[] = "v_vec.dat";
    char caminho_A[] = "A_array.dat";
    char caminho_B[] = "B_array.dat";
    Import_vec(Nk,caminho_u,u,1);
    Import_vec(Nj,caminho_v,v,0);
    Import_array(Ni,Nk,caminho_A,A,0);
    Import_array(Nk,Nj,caminho_B,B,0);

    //Definição de C
    float **C = Alloc_array(Ni,Nj);
    for(int i = 0;i<Ni;i++)
    {
        for(int j=0;j<Nj;j++)
        {
            C[i][j] = 0;
            for(int k = 0;k<Nk;k++)
            {
                C[i][j] += A[i][k]*B[k][j];
            }
        }
    }
    //Definição de s
    float *s = Alloc_vec(Nk);
    for(int i = 0;i<Ni;i++)
    {
        s[i] = 0;
        for(int j=0;j<Nk;j++)
        {
            s[i] += A[i][j]*u[j];
        }
    }


    //Definição de r
    float *r = Alloc_vec(Nj);
    for(int i = 0;i<Ni;i++)
    {
        r[i] = 0;
        for(int j=0;j<Nj;j++)
        {
            r[i] += C[i][j]*v[j];

        }
        float numero = r[i];
        printf("%f",numero);
    }
    float z=0;
    for(int i = 0;i<Ni;i++)
    {
        z+=r[i]*s[i];
    }
   // printf("%f",z);
    for(int i = 0;i<Ni;i++)
    {
        free(A[i]);
    }
    free(A);
    for(int i = 0;i<Nk;i++)
    {
        free(B[i]);
    }
    free(B);
    for(int i = 0;i<Ni;i++)
    {
        free(C[i]);
    }
    free(C);
    free(r);
    free(s);
    free(u);
    free(v);
    return 0;
}

1 answer

0

Good night, Lamparejo

I took a look at your code and it was not very clear the formatting of the contents of the file you are reading, which in this case makes all the difference.

To try to help you what I did: I created a program that records and reads from a single file a sequence of 5 floats.

The recording is "fixed" with the first values you reported.

Already the reading, feeds dynamically a vector of floats, to its maximum length 5(could be 10, 20, whatever). I hope it is of use to you. I see that your problem may be in the logic of "counting" the positions of your array. If you need more help, don’t hesitate to ask! In time, send also the file and if you need me to do also using malloc.

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

#define TAMANHO_VETOR 5

int escreve_arquivo_vetor(){
    FILE *arquivoVetor;
    char *caminhoArquivoVetor = "arquivo_vetor.dat";
    
    if ( (arquivoVetor = fopen(caminhoArquivoVetor, "w")) == NULL )
        return -1;
        
    fprintf(arquivoVetor,
    "%f\n%f\n%f\n%f\n%f\n",
        0.918033,
        -0.981341,
        0.241689,
        2.344740,
        -1.605030
    );
    fclose(arquivoVetor);
    return 0;
}

void le_arquivo_vetor(float *vetorFloat){
    FILE *arquivoVetor;
    char *caminhoArquivoVetor = "arquivo_vetor.dat";
    char fileLine[128];
    int i = 0;
    
    if ( (arquivoVetor = fopen(caminhoArquivoVetor, "r")) == NULL )
        return;
    
    while ( fgets(fileLine, sizeof(fileLine), arquivoVetor) ){
        vetorFloat[i++] = atof(fileLine);
        if ( i >= TAMANHO_VETOR ) break;
    }
}

void imprime_vetor(float *vetorFloat){
    int i = 0;
    
    while ( i < TAMANHO_VETOR )
        printf ("vetorFloat[%d]=%f\n", i, vetorFloat[i++]);
    
    return;
}

int main(){
    float vetorFloat[TAMANHO_VETOR];
    float matrizFloat[5][5];
    
    if ( escreve_arquivo_vetor() < 0 )
        printf("erro ao escrever arquivo");
        
    le_arquivo_vetor(vetorFloat);
    
    imprime_vetor(vetorFloat);
        
    return 0;
} 
  • The files follow this format: Those of vectors: (u_vec) 0.918033 -0.981341 0.241689 2.34474 -1.60503 -1.39559 -1.28021 1.80147 -0.216157 -1.63404 , and the matrix one is very large, but it is done as expected: rows and columns with their respective elements.

Browser other questions tagged

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