Reading data from the file is correct, owner, phone, tariff get values and output to the console, but when I pass them to the function, the owner pointer for some reason becomes empty and is not output when calling preOrder, although phone does not lose the pointer and is output to the console. What might be the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char owner[10];
char phone[12];
int tariff;
struct node *left, *right;
} NODE, *pNODE;
pNODE addNode(char * owner, char * phone, int tariff, pNODE root);
void preOrder(pNODE root);
int main() {
srand(time(NULL));
pNODE root = NULL;
FILE* fp;
fp = fopen("./source/data.txt", "r");
char owner[10];
char phone[12];
int tariff;
while(!feof(fp)){
fscanf(fp, "%s", &owner);
printf("%s ", owner);
fscanf(fp, "%s", &phone);
printf("%s ", phone);
fscanf(fp, "%d", &tariff);
printf("%d\n", tariff);
root = addNode(owner, phone, tariff, root);
}
fclose(fp);
printf("%s\n", root->owner);
preOrder(root);
return 0;
}
pNODE addNode(char * owner, char * phone, int tariff, pNODE root){
if(!root){
root = malloc(sizeof(NODE));
if(root){
strcpy(root->owner, owner);
strcpy(root->phone, phone);
root->tariff = tariff;
root->left = NULL;
root->right = NULL;
}
}
else
if(tariff < root->tariff)
root->left = addNode(owner, phone, tariff, root->left);
else
root->right = addNode(owner, phone, tariff, root->right);
return root;
}
void preOrder(pNODE root){
if(root){
printf("%s %s %d", root->owner, root->phone, root->tariff);
preOrder(root->left);
preOrder(root->right);
}
}
Data in the file:
Ivan +79857465656 1
Mark +78345674534 2
Tom +78937478383 1
Petr +78293338475 3
Anna +79883743737 4