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]);
  }

}
4

3 回答 3

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 */
  }
于 2012-10-22T10:46:54.797 回答
1

sscanf 解析一个字符串(它的第一个参数),但 nextfreeplace 是一个指向 int 的指针。它也被作为 NULL 指针传递给 insert。

于 2012-10-22T10:43:58.973 回答
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;
}

您的代码接近您想要的。请注意两个示例之间的差异。在编译器中启用所有警告并遵循它们。

于 2012-10-22T10:48:47.443 回答