hello i have a task to do the teacher specified that we must do our program with agency list so the first part of the program must be a representing a graph and i did it the second part is that the user enter a letter after a number or a number after a lettre using this graph representation like for example if you enter "4gk2" the output should be "wrong" and if you enter "4f5b" the output should be "correct" can anyone help me with this program am so stuck
here's the the graph i represented in C can anyone complete it please
#include <stdio.h>
#include <stdlib.h>
int no_nodes;
struct node {
int data;
int number;
char lettre;
struct node *next;
};
void readAutomat(struct node *tab[]) {
struct node *newnode;
int k, data;
for (int i = 0; i < no_nodes; i ) {
struct node *last;
printf("How many nodes are adjacent to %d", i);
scanf("%d", &k);
for (int j = 1; j <= k; j ) {
newnode = (struct node *)malloc(sizeof(struct node *));
printf("Enter the %d neighbour of %d :", j, i);
scanf("%d", &data);
newnode->data = data;
newnode->next = NULL;
if (tab[i] == NULL) {
tab[i] = newnode;
} else {
last->next = newnode;
}
last = newnode;
}
}
}
void printAutomat(struct node *tab[]) {
struct node *temp;
for (int i = 0; i < no_nodes; i ) {
temp = tab[i];
printf("Vertices Adjacent to %d are :", i);
while (temp != NULL) {
printf("%d\t", temp->data);
temp = temp->next;
}
}
}
int main() {
printf("Enter the numbers of nodes");
scanf("%d", &no_nodes);
struct node *tab[no_nodes];
for (int i = 0; i < no_nodes; i ) {
tab[i] = NULL;
}
readAutomat(tab);
printAutomat(tab);
return 0;
}
CodePudding user response:
This is wrong
newnode=(struct node *)malloc(sizeof(struct node *));
it creates space for a pointer not for the node struct , you need
newnode=(struct node *)malloc(sizeof(struct node));
or more idiomatically
newnode=(struct node *)malloc(sizeof(*newnode));
and even better - as per https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc#:~:text=In C, you don't,compiler, a cast is needed.
newnode=malloc(sizeof(*newnode));