2012-10-22 140 views
0

我想使參數作爲參考,所以我可以在我的主要功能中使用「nextfreeplace」。問題是我沒有真正理解將參數作爲參考的術語。任何人都可以請幫忙。我也收到了編譯警告。使參數作爲參考

#include <stdio.h> 
#include <stdlib.h> 


/* these arrays are just used to give the parameters to 'insert', 
    to create the 'people' array */ 
char *names[7]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim", 
      "Harriet"}; 
int ages[7]= {22, 24, 106, 6, 18, 32, 24}; 


/* declare your struct for a person here */ 
typedef struct{ 
    char *names; 
    int ages; 
} person; 

static void insert (person **p, char *s, int n, int *nextfreeplace) { 

*p = malloc(sizeof(person)); 

/*static int nextfreeplace = 0;*/ 

/* put name and age into the next free place in the array parameter here */ 
(*p)->names=s; 
(*p)->ages=n; 


    /* make the parameter as reference*/ 
    sscanf(nextfreeplace,"%d", *p); 


    /* modify nextfreeplace here */ 
    (*nextfreeplace)++; 

    } 

int main(int argc, char **argv) { 

    /* declare nextinsert */ 
    int *nextfreeplace = 0; 


    /* declare the people array here */ 
    person *p[7]; 

    //insert the members and age into the unusage array. 
    for (int i=0; i < 7; i++) { 
    insert (&p[i], names[i], ages[i], nextfreeplace); 
    /* do not dereference the pointer */ 
    } 

    /* print the people array here*/ 
    for (int i=0; i < 7; i++) { 
    printf("The name is: %s, the age is:%i\n", p[i]->names, p[i]->ages); 
    } 


    /* This is the third loop for call free to release the memory allocated by malloc */ 
    /* the free()function deallocate the space pointed by ptr. */ 
    for(int i=0; i<7;i++){ 
    free(p[i]); 
    } 

} 

回答

1

sscanf解析一個字符串(它的第一個參數),但nextfreeplace是一個指向int的指針。它也被傳遞爲插入爲NULL指針。

2

這應該更改爲下面的代碼,因爲(*nextfreeplace)++;將嘗試訪問地址0x000000000,這可能會導致segmentation fault

int nextfreeplace = 0; 


    /* declare the people array here */ 
    person *p[7]; 

    //insert the members and age into the unusage array. 
    for (int i=0; i < 7; i++) { 
    insert (&p[i], names[i], ages[i], &nextfreeplace); 
    /* do not dereference the pointer */ 
    } 
1

這對案件的普通術語,當你傳遞不是的東西作爲參數拷貝,但的東西的位置,這樣你就可以修改它在函數中。

例1:

int add(int x, int y) 
{ 
    int s = x + y; 
    x = 0; // this does not affect x in main() 
    return s; 
} 

int main(void) 
{ 
    int x = 1, y = 2, sum; 
    sum = add(x, y); 
    return 0; 
} 

例2:

int add(int* x, int y) 
{ 
    int s = *x + y; 
    *x = 0; // this affects x in main() 
    return s; 
} 

int main(void) 
{ 
    int x = 1, y = 2, sum; 
    sum = add(&x, y); 
    return 0; 
} 

你的代碼是接近你想要什麼。請注意兩個示例之間的差異。在您的編譯器中啓用所有警告並按照它們執行。