1
新しいノードを追加して表示する機能を持つ構造体を作成するプログラムで作業しています。私は "add"と呼ばれる関数を持っています。新しいノードを作成してstruct-> nextに送信しますが、関数 "displayData"を実行しようとするたびに、構造体はNULL /空です。ポインタを使って構造体を作成する
ここにコードがあります。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
struct node {
int item;
nodePtr next;
};
typedef nodePtr Statistician;
int input();
Statistician newStatistician(); //allocates memory to the structure. Dynamic allocation
void add(Statistician s, int x); //Adds data to the rear
void displayData(Statistician s); //prints entire dataset
int main() {
int operation, data;
Statistician s = NULL;
data = input(); //get new input
add(s,data); //run add function
displayData(s); //run display function
}
int input(){
int x;
printf("Enter data: ");
if (scanf("%d", &x) != 1)
{
printf("\n\nInvalid Input!\n\n");
exit(0);
}
return x;
}
Statistician newStatistician(){
Statistician newStat;
newStat = malloc(sizeof(struct node));
return newStat;
}
void add(Statistician s, int x){
Statistician newNode = newStatistician();
newNode->item = x;
newNode->next = NULL;
if(s == NULL){
s = newNode;
return;
}
while (s != NULL) {
s = s->next;
}
s->next = newNode;
}
void displayData(Statistician s){
Statistician temp = s;
if(s==NULL){
printf("\n\nList is EMPTY.");
printf("\n\nPress any key.\n");
getch();
return;
}
printf("\n\nThe List:\n");
while (temp != NULL) {
printf(" %d", temp->item);
temp = temp->next;
}
printf("\n\nPress any key.\n");
getch();
return;
}
私がdisplayDataを使用すると、出力は次のようになります。
List is EMPTY
おかげのように呼び出すことができます! –
@FrancisM全くありません。どういたしまして。:) –