Search code examples
cfunctioncalloc

C programming reading from file using functions & calloc


I am having trouble utilizing functions to get the second calloc of my program to read from file work correctly. The function to be called is colAlloc (variables).

My code below is:

void readSpaces (FILE * ptrF, char fileN [], double ** m, int * r)
{
    ptrF = fopen (fileN, "r");

    char s;
    int i;
    int ctrS = 0;
    int c;
    int cVal;

    for (s = getc (ptrF); s != EOF; s = getc (ptrF))
    {
        if (s == ' ' || s == '\t' || s == '\t')
        {
            ++ctrS;
        }
    }
    cVal = ctrS / * r;

    c = cVal;

    colAlloc (ptrF, fileN, m, &r, &cVal);

    /**something is not working here so the program is giving a run-time error once it needs to read column**/

    fclose (ptrF);
}

//allocate memory for column
void colAlloc (FILE * ptrF, char fileN [], double ** m, int ** r, int ** s) //file pointer, file name, matrix, row, spaces;
{
    int i;
    int c;

    c = & s;

    for (i = 0; i < * r; i ++ )
    {
        m [i] = (double *) calloc (c, sizeof (double));
        if (m [i] == NULL)
        {
            printf ("\nSorry, not enough memory!\n\n");
            exit (0);
        }
    }
    printf ("Cols >> %d.\n\n", c);

    for (i = 0; i < * r; i ++)
    {
        free (m [i]);
    }

}

When I call the function in the readSpaces (ptrF, fileN, m, r) function, the program just crashes. I think I am calling the function wrong, and is confusing the use of pointers and call by reference for the appropriate variables.

Some help would be much appreciated.

Thanks


Solution

  • for (i = 0; i < * r; i ++ )
    

    r is of int **, so i < *r compares an int (i) to an int * (*r). In other words you are comparing against an address, which is not what you intended.