sorin.va
sorin.va

Reputation: 41

Reallocating same array seems to not work

This is the code snippet, it belongs to a bigger project. Basicly it has to store and print how many times a character appears in a block of text. What i dont really seem to understand is how to reallocate the same array....

void subiect2_subpunct_c(char* nume_fisier)
{
    FILE *f1;
    char a;
    int i = 0, j, ok;
    char *caracter, *tempc;
    int *frecventa, *tempf;

    caracter = (char*)malloc(sizeof(char));
    frecventa = (int*)malloc(sizeof(int));

    f1 = fopen(nume_fisier, "r");

    while (a = fgetc(f1))
    {
        ok = 0;

        if (i == 0)
        {
            frecventa[i] = 1;
            caracter[i++] = a;
        }
        else
        {
            for (j = 0; j < i; j++)
            {
                if (caracter[j] == a)
                {
                    frecventa[j]++;
                    j = i;
                    ok = 1;
                }
            }

            if (ok == 0)
            {
                tempc = (char*)realloc(caracter, (i + 1)*sizeof(char));
                tempf = (int*)realloc(frecventa, (i + 1)*sizeof(int));

                caracter = tempc;
                frecventa = tempf;

                frecventa[i] = 1;
                caracter[i++] = a;
            }
        }
    }

    for (j = 0; j < i; j++)
    {
        printf("\n %c (%d)", caracter[j], frecventa[j]);
    }

    fclose(f1);
}

Upvotes: 0

Views: 51

Answers (1)

francis
francis

Reputation: 9817

The trouble does not come from realloc(). If you read a file and read characters in it, you should check a few facts as shown here http://www.cplusplus.com/reference/cstdio/fgetc/ :

  • The file is successfully opened : test the result of fopen() :

      f1 = fopen(nume_fisier, "r");
      if(f1==NULL)perror ("Error opening file");
    
  • The end of the file has not been reached : test the result of fgetc()

     a=fgetc(f1);
     while(a!=EOF){
        ...
        a=fgetc(f1);
     }
    

Your code failed because a=fgetc(f1) is always true (i don't know why !) : the program never got out of the while loop.

Bye,

Francis

Upvotes: 2

Related Questions