2010-06-08 197 views
0

我是c編程新手。任何人都可以告訴我 下面的程序有什麼問題嗎?c指向指針或將函數傳遞給函數的指針


typedef struct Person_s 
{ 
    int age; 
    char name[40]; 
} Person_t; 


int process_list(int *countReturned, Person_t **p_list) 
{ 

    Person_t *rowPtr=0; 
    //the actual program will fethc data from DB 

    int count =1; 

if(!((*p_list) = (Person_t *) malloc(sizeof(Person_t)))) 
{ 
    return -1; 
} 

rowPtr = *p_list; 

rowPtr[count-1].age =19; 
strcpy(rowPtr[count-1].name,"Prince Dastan"); 
*countReturned = count; 

    return 0; 
} 


int main(int argc, char *argv[]) 
{ 
     Person_t *tmpPerson=0; 
     Person_t **p_list=0; 
     int *count=0; 
     int i; 

     process_list(count,p_list); 

     tmpPerson = *p_list; 

     for(i=0; i< *count; i++) 
     { 
      printf("Name: %s , age: %d\n",tmpPerson->name,tmpPerson->age); 
      tmpPerson++; 
     } 

     //free(tmpPerson); 

    return 0; 
} 
+0

你是在尋找代碼審查還是有特定的錯誤?如果是這樣,問題是什麼? – 2010-06-08 21:09:15

回答

1

你應該有主:

Person_t *p_list=0; 
... 
process_list(count, &p_list); 

代碼爲0到process_list書面通行證,然後你有:

*0 = (Person_t *)malloc(...); 

這將導致0是解除引用,您的代碼將崩潰。

+0

將'count'傳遞給'count'聲明爲'int * count = 0'仍然會導致NULL和崩潰。 – Chuck 2010-06-08 21:15:05

0

輸入函數時p_list的值爲0.如果解引用0,則會發生總線錯誤。

if(!((*p_list) = (Person_t *) malloc(sizeof(Person_t)))) 

(章C問題90%是由提領一空指針引起的,Java的問題,就像90%是由錯誤配置類路徑引起的。:-)

3

你的問題是,你」重新設置指針指向NULL(0),然後解引用它們。您不允許取消引用NULL。想你想要的是更多這樣的:

int main(int argc, char *argv[]) 
{ 
     Person_t tmpPerson; 
     Person_t *p_list=0; 
     int count; 
     int i; 

     process_list(&count, &p_list); 

     tmpPerson = *p_list; 
     // and so on... 

&是運營商,它返回一個指針變量的地址,在「地址的」。所以這通過了一個指向countp_list的指針,然後你的函數用它來設置這些變量,這似乎是你想要做的。

+0

我需要從process_list()函數中檢索具有count的列表。 「Person_t * p_list = 0;」這會返回一個列表嗎? – Nazrul 2010-06-08 21:15:10

+0

@ user361808:它返回一個指向「Pointer_t」數組的指針(其中數組實際上可能只是一個Pointer_t,就像在你的測試代碼中一樣)。 – Chuck 2010-06-08 21:18:39