私はC++で簡単な関数を書いています。リストの先頭に挿入
私のコードでエラーが発生します。出力はありません。
また、私は次のインデックスが記憶された後に無料で電話する必要があります。 私はそれを行う方法を知らない。 printfの後にwhileループ内で電流を解放する必要がありますか?
static person* insert(person *headptr, char *name, int age)
{
if (headptr == NULL) {
headptr = (person*)malloc(sizeof(person));
headptr->name = name;
headptr->age = age;
headptr->next = NULL;
}
else{
person *ptr = (person*)malloc(sizeof(person));
if (ptr == NULL) abort();
//assign to structure field
ptr->name = name;
ptr->age = age;
//link new object into the list
ptr->next = headptr;
headptr = ptr;
}
return headptr;
}
そして今、あなたは以下のように上記のメソッドを呼び出す必要があります: - - :
今// Make a copy of the pointer to the head item in the list
for (int index=0;index < HOW_MANY;index=index+1)
{
headptr = insert(headptr, *(names+index), ages[index]);
}
ここにあなたが以下のようなあなたのinsert
方法を変更する必要が私のコード
#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};
/* declare your struct for a person here */
typedef struct{
char* name;
int age;
struct person *next;
}
person;
static void insert(person *headptr, char *name, int age)
{
person *ptr=malloc(sizeof(person));
if(ptr==NULL) abort();
//assign to structure field
ptr->name = name;
ptr->age = age;
//link new object into the list
ptr->next=headptr;
headptr=ptr;
}
int main(int argc, char **argv)
{
/* declare the people array here */
person *headptr=NULL;
// Make a copy of the pointer to the head item in the list
for (int index=0;index < HOW_MANY;index=index+1)
{
insert(headptr, *(names+index), ages[index]);
}
person *current=NULL;
// current will be set to NULL when it reaches the end
while(current != NULL)
{
// print out the item information
printf("name: %s, age: %i\n",current -> name, current-> age);
// Now move to the next item in the linked list
current= current -> next;
}
}
「自分のコードでエラーが発生します。 – DimChtz
現在の値にnullを割り当て、whileループでそれをテストします。 –
警告:互換性のないポインタ型からの割り当て[デフォルトで有効] ptr-> next = headptr; ^ lists.c:関数 'main': lists.c:52:14:警告:互換性のないポインタ型からの割り当て[デフォルトで有効] current = current - > next; –