简体   繁体   English

使用函数和Calloc从文件读取C编程

[英]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. 我无法利用函数来获取程序的第二个calloc来从文件中正确读取文件。 The function to be called is colAlloc (variables) . 要调用的函数是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. 当我在readSpaces (ptrF, fileN, m, r)函数中调用该函数时,该程序只是崩溃了。 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 谢谢

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

r is of int ** , so i < *r compares an int ( i ) to an int * ( *r ). r是int ** ,因此i < *r将int( i )与int **r )进行比较。 In other words you are comparing against an address, which is not what you intended. 换句话说,您正在与一个地址进行比较,这不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM