-1

当这个函数从它的调用中返回时,我似乎无法从中打印任何东西。当我尝试从函数内打印时,它可以正常工作,但在调用后不会打印。不知道该怎么办。

    int *sched;
    getSchedFile(schFile, sched);
    printf("%d\n",sched[1]);

void getSchedFile (FILE *file, int *schd){
    /* Get the number of bytes */
    fseek(file, 0L, SEEK_END);
    int bytes = ftell(file);
    fseek(file, 0L, SEEK_SET);
    schd = malloc(bytes * sizeof(int));
    int pos = 0, curDigit;
    while((fscanf(file, "%d", &curDigit)) != EOF){
        schd[pos]=curDigit;
        ++pos;
    } 
}
4

1 回答 1

1

您应该通过更改将指针传递给您的指针:

getSchedFile(schFile, sched);

至:

getSchedFile(schFile, &sched);

和:

void getSchedFile (FILE *file, int *schd) {

至:

void getSchedFile (FILE *file, int ** schd) {

否则,您只是更改函数中指针的本地版本,而不是原始版本。为了简单起见,避免过多的间接,您可以将函数更改为:

void getSchedFile (FILE *file, int ** schd) {

    /* Get the number of bytes */

    fseek(file, 0L, SEEK_END);
    int bytes = ftell(file);
    fseek(file, 0L, SEEK_SET);

    int * pschd = malloc(bytes * sizeof(int));
    if ( pschd == NULL ) {
        fprintf(stderr, "Couldn't allocate memory.\n");
        exit(EXIT_FAILURE);
    }

    int pos = 0, curDigit;
    while((fscanf(file, "%d", &curDigit)) != EOF){
        pschd[pos]=curDigit;
        ++pos;
    } 

    *schd = pschd;  /*  Update original pointer  */
}

正如查理提到的,如果您使用 读取%d,那么文件中的字节数将int与您从中读取的 s 数不同,尽管您至少不会分配太少的内存。

编辑:您可能还想给函数一个返回类型int和 return pos - 1,以便调用者知道您的新数组中有多少元素(或最后一个元素的索引,只返回pos实际的元素数量)。

于 2013-10-13T04:33:47.473 回答