我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:
在声明后,我按照以下方式将学生添加到数组中(仅作为示例...):
我用这段代码调用函数:
但现在我的问题是:在我的“add_student”函数中,我得到一个具有奇怪结构的数组:它将自身作为第一个元素,并且每个其他元素都向后移动了1个元素。
我正在编写一个程序,在其中需要将学生添加到结构体数组中。
好的,一开始我有以下结构体数组:
struct student *students[4];
在声明后,我按照以下方式将学生添加到数组中(仅作为示例...):
students[0] = malloc(sizeof(struct student));
students[0]->firstname = "Max";
students[0]->secondname = "Taler";
students[0]->number = 123456l;
...
现在我需要编写一个额外的函数,其中我可以将数组作为参数传递并添加新学生。 因此,我的函数看起来像这样:void add_student(struct student *students[],char *fristname, char *secondname, long number)
{
int i=0;
int new_position=0;
int return_value = 0;
// Search for the first available position for a new student
for(i=0; i<sizeof(students); i++)
{
if(students[i]==NULL)
{
new_position=i;
return_value = 1;
break;
}
}
struct student *new_student = malloc(sizeof(struct student));
students[new_position] = new_student;
students[new_position]->fristname = fristname;
students[new_position]->secondname = secondname;
students[new_position]->number = number;
return return_value;
}
我用这段代码调用函数:
add_student(students, "Anni", "Karls", 123232);
但现在我的问题是:在我的“add_student”函数中,我得到一个具有奇怪结构的数组:它将自身作为第一个元素,并且每个其他元素都向后移动了1个元素。
无法弄清楚问题所在... 有人可以帮忙吗?
编辑:有人问我,这怎么可能。数组如何包含自己作为第一个元素。
好吧,这里是调试器(xCode)的截屏:
进入“add_student”之前:
在输入“add_student”后,进入函数“add_student”:正如您所见,“students”现在有5个元素...
i<sizeof(students)
没有做你期望的事情。 - haccksvoid add_student(...) { ... return return_value; }
是一个问题。void
函数不返回值。 - chux - Reinstate Monica