基本的に以下のコードでは、いくつかの名前といくつかの年代をリストに入れて印刷しようとしています。しかし、私のプログラムはリストの最後の名前と年齢だけを表示します。助言がありますか?Cのリストの要素を印刷
#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
typedef struct person
{
char *name;
int age;
struct person *next;
}Person;
Person *headp = NULL;
static Person* insert(Person *p, char *name, int age)
{
p = (Person*)malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
p->next = headp;
return p;
}
int main(int argc, char **argv)
{
Person *people=headp;
for (int i = 0; i < 7; i++)
{
people = insert (people, names[i], ages[i]);
}
while (people != NULL)
{
printf ("name: %s, age: %i\n", people->name, people->age);
people= people->next;
}
return 0;
}
それが動作している....しかし、それは要素を出力します逆の順序で...すなわち最初の要素は最後の要素です... –
次にfor(int i = 0; i <7; i ++)を 'for(int i = 6; i> = 0; i - )に変更します ' –
@RalucaDamarisLupeş :これはどうやって驚きですか? 'insert'関数は、' append'ではなく 'prepend'のように動作するように設計しました。 –