2012-10-22 3 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; 
} 

Ваш код близок к тому, что вы хотите. Обратите внимание на различия между двумя примерами. Включите все предупреждения в своем компиляторе и следуйте им.

Смежные вопросы