2013-10-13 190 views
-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; 
    } 
} 
+0

您正将'sched'指针中包含的值的*副本传递给该函数。在函数内部,您将* copy *的值设置为您malloc的内存地址。由于您传递的是存储在指针中的值,而不是包含指针的内存地址,因此所做的任何更改都将被丢弃。如果你传递'* sched'的地址,那么你可以改变它('sched')指向的位置 - 也可以坚持所做的更改。 – enhzflep

+0

[在C中传递char指针]的可能重复(http://stackoverflow.com/questions/14331411/passing-char-pointer-in-c) – 2013-10-13 05:08:10

+0

这个'^^'**实际上是Google * *“传递指针不起作用C”。为什么不问研究之前呢? – 2013-10-13 05:08:47

回答

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,尽管您至少不会分配太少的内存。

编辑:您也可能想给该函数返回类型的int并返回pos - 1,使来电者知道有多少元素在新数组(或最后一个元素的索引,只返回pos为实际数量的元素)。

+0

谢谢你的工作。是的,我知道%d意味着过度分配,但我不知道有任何其他方式来做到这一点。我认为至少这是一个粗略的估计。 – Boyo

+0

@ThomasTheTankEngine:你至少可以做'(bytes/2)+ 1',因为最坏的情况会是一个数字,然后是一个空白字符,一直到文件末尾。第二种方法是在空间效率更高但时间效率更低的情况下,可以通过文件并对它们进行计数,分配正确的内存量,然后再次进行实际读取和存储。一旦知道必要的尺寸,调用'realloc()'是另一种选择。 –