Linked List inside Linked List - c

I'm trying to use nested linked lists, but I can't seem to access the inner part of the linked list.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int option;
struct nodeAddr
{
int idAddress;
char address[50];
struct nodeAddr *nextAddr;
}*headAddr,*tailAddr,*newAddr,*helpAddr;
struct nodePrs
{
int idPersonel;
char personel[50];
struct nodeAddr *headAddr,*tailAddr,*newAddr,*helpAddr ;
struct nodePrs *nextPrs;
}*headPrs,*tailPrs,*newPrs,*helpPrs;
void signUp()
{
clrscr();
printf("\t============================\n");
printf("\t= Sign Up New Personel =\n");
printf("\t============================\n\n");
newPrs=(nodePrs*)malloc(sizeof(struct nodePrs));
newPrs->newAddr=(nodeAddr*)malloc(sizeof(struct nodeAddr));
printf("Name : ");
scanf("%s",newPrs->personel);
printf("Address : ");
scanf("%s",newPrs->newAddr->address);
newPrs->nextPrs = NULL;
newPrs->newAddr->nextAddr = NULL;
if (headPrs==NULL)
{
headPrs = newPrs;
headPrs->headAddr = newPrs->newAddr;
}
else
{
tailPrs->nextPrs=newPrs;
}
tailPrs=newPrs;
tailPrs->tailAddr=newPrs->newAddr;
}
void printList()
{
helpPrs = headPrs;
nodePrs *temp = headPrs;
if (headPrs==NULL)
printf("Empty");
else
{
printf("the Outputs:\n");
while(helpPrs!=NULL)
{
printf("%s", helpPrs->personel);
printf(" ");
helpPrs->helpAddr = temp->headAddr;
while (helpPrs->helpAddr !=NULL)
{
printf("%s", helpPrs->helpAddr->address);
printf(" ");
helpPrs->helpAddr = helpPrs->helpAddr->nextAddr;
}
helpPrs = helpPrs->nextPrs;
temp=temp->nextPrs;
printf("\n");
}
}
}
void main()
{
do
{
clrscr();
printf("\t==================================\n");
printf("\t= Linked list inside Linked List =\n");
printf("\t==================================\n\n");
printf("1. Sign\n");
printf("2. Show\n");
printf("3. Exit\n\n");
printf("Input (1-3) : ");
scanf("%d",&option);
if (option == 1)
{
signUp();
}
else if (option == 2)
{
printList();
getch();
}
else if(option>2 || option <1)
{
printf("Wrong choice!!!");
}
} while(option!=5);
getch();
}
The problem is in the printList() function. It only prints the first list. After that, it can't show its address of the second entry and so on.

Related

When allocating memory for a stack in a stack using malloc, it returns NULL

I have an issue with dynamic memory. I have a stack with information about the length of an array, and a pointer to another stack. The end goal is to make a shoppinglist with a list of items that keeps expanding as the user adds them. It consists of three files.
I am quite new to coding so this issue might (hopefully) be an easy fix.
ShoppingList.h
#ifndef SHOPPING_LIST_H
#define SHOPPING_LIST_H
#define SIZE 100
/*Här lägger du eventuella makrodefinitioner*/
// Struct definitions
struct GroceryItem {
char productName[SIZE];
float amount;
char unit[SIZE];
};
struct ShoppingList{
struct GroceryItem *itemList;
int length;
};
// Function declarations
void addItem(struct ShoppingList *list);
void printList(struct ShoppingList *list);
void editItem(struct ShoppingList *list);
void removeItem(struct ShoppingList *list);
void saveList(struct ShoppingList *list); //implementeras i laboration 7
void loadList(struct ShoppingList* list); //implementeras i laboration 7
#endif
This is the file containing the main function that calls different funktions in the third file.
#define _CRT_SECURE_NO_WARNINGS
#include "ShoppingList.h"
#include <stdio.h>
#define CLEAR while(getchar() != '\n');
int main(void)
{
struct ShoppingList shoppingList;
shoppingList.length = 0; // The shopping list is empty at the start
shoppingList.itemList = NULL;
int option;
do
{
printf("\n\nWelcome to the shopping list manager!\n");
printf("=====================================\n\n");
printf("1. Add an item\n");
printf("2. Display the shopping list\n");
printf("3. Remove an item\n");
printf("4. Change an item\n");
printf("5. Save list\n");
printf("6. Load list\n");
printf("7. Exit\n");
printf("What do you want to do? ");
scanf("%d", &option); CLEAR
switch (option)
{
case 1: addItem(&shoppingList); break;
case 2: printList(&shoppingList); break;
case 3: removeItem(&shoppingList); break;
case 4: editItem(&shoppingList); break;
case 5: saveList(&shoppingList); break;
case 6: loadList(&shoppingList); break;
case 7: break;
default:
printf("Please enter a number between 1 and 7");
}
} while (option != 7);
return 0;
}
This is the file where all the functions containing code on how to add an item, delete etc. The last function containing the dynamic memory allocation with malloc and realloc does not work and I can't figure out what is causing it.
#define _CRT_SECURE_NO_WARNINGS
#include"ShoppingList.h"
#include<stdio.h>
#include<stdlib.h> // For dynamic memory (lab 7)
#include <string.h>
#define CLEAR while(getchar() != '\n');
void enterProductName(struct ShoppingList* plist);
void enterUnit(struct ShoppingList* plist);
void negativeCheck(struct ShoppingList* plist);
void editItem(struct ShoppingList* list);
void editItemMenu(struct ShoppingList* list);
void itemDeleter(struct ShoppingList* list, int deleteThis);
int memoryAllocator(struct ShoppingList** ListInMemory, int length);
void memoryReturn(struct ShoppingList* list);
void addItem(struct ShoppingList* list)
{
int error = 0;
error = memoryAllocator(list->itemList, list->length);
if (error == 0)
return;
enterProductName(list);
negativeCheck(list);
enterUnit(list);
printf("This item has been added!\n\n");
list->length = list->length + 1;
return;
}
void printList(struct ShoppingList *list)
{
if (list->length == 0) {
printf("\nYour shoppinglist is empty! Start by adding an item.");
return;
}
printf("\nYour shopping list\n\n");
printf("Nr Item\t\t Ammount\tUnit\n");
for (int i = 0; i < 5 && i < list->length; i++) {
printf("%d. %-20s", i+1, list->itemList[i].productName);
printf("%-8.1f %s\n", list->itemList[i].amount, list->itemList[i].unit);
}
}
void editItem(struct ShoppingList *list)
{
printf("\nYour shopping list\n\n");
printf("Nr Item\t\t Ammount\tUnit\n");
for (int i = 0; i < 5 && i < list->length; i++) {
printf("%d. %-20s", i + 1, list->itemList[i].productName);
printf("%-8.1f %s\n", list->itemList[i].amount, list->itemList[i].unit);
}
editItemMenu(list);
}
void removeItem(struct ShoppingList *list)
{
int itemToDelete = 0, itemDeleteConfirm = 0;
if (list->length == 0) {
printf("Your shopping list is empty.");
}
else {
printf("\nYour shopping list\n\n");
printf("Nr Item\t\t Ammount\tUnit\n");
for (int i = 0; i < 5 && i < list->length; i++) {
printf("%d. %-20s", i + 1, list->itemList[i].productName);
printf("%-8.1f %s\n", list->itemList[i].amount, list->itemList[i].unit);
}
printf("\nEnter the number of the item you with to delete: ");
scanf("%d", &itemToDelete); CLEAR
printf("Are you sure you want to delete this item? 0 - no, 1 - yes: ");
scanf("%d", &itemDeleteConfirm);
if (itemDeleteConfirm == 1)
{
itemDeleter(list, itemToDelete);
}
}
}
/*saveList och loadList implementeras i laboration 7*/
void saveList(struct ShoppingList *list)
{
free(list->itemList);
}
void loadList(struct ShoppingList* list)
{
}
void enterProductName(struct ShoppingList* plist) {
printf("Enter item name: ");
fgets(plist->itemList[plist->length].productName, SIZE, stdin);
plist->itemList[plist->length].productName[strlen(plist->itemList[plist->length].productName) - 1] = '\0';
}
void enterUnit(struct ShoppingList* plist) {
printf("Enter the unit (e.g. kg): ");
fgets(plist->itemList[plist->length].unit, SIZE, stdin);
plist->itemList[plist->length].unit[strlen(plist->itemList[plist->length].unit) - 1] = '\0';
}
void negativeCheck(struct ShoppingList* plist) {
int ammountNegative = 1;
do {
printf("Enter ammount: ");
scanf("%f", &plist->itemList[plist->length].amount); CLEAR
if (plist->itemList[plist->length].amount < 0) {
printf("\nYou can only enter positive numbers!\n");
ammountNegative = 1;
}
else
ammountNegative = 0;
} while (ammountNegative != 0);
}
void editItemMenu(struct ShoppingList *list) {
int editItemWhat = 0;
int editItemNumber = 0;
printf("\nWhat item would you like to edit?");
printf("\nEnter the items number to edit it: ");
scanf("%d", &editItemNumber); CLEAR
printf("What would you like to edit?\n");
printf("1. Name\n");
printf("2. Ammount\n");
printf("3. Unit\n");
printf("\nEnter number to edit: ");
scanf("%d", &editItemWhat); CLEAR
editItemNumber--;
switch (editItemWhat)
{
case 1:printf("Enter new name: "); fgets(list->itemList[editItemNumber].productName, SIZE, stdin);
list->itemList[editItemNumber].productName[strlen(list->itemList[editItemNumber].productName) - 1] = '\0'; break;
case 2:printf("Enter new ammount: "); scanf("%f", &list->itemList[editItemNumber].amount); break;
case 3:printf("Enter new unit: "); fgets(list->itemList[editItemNumber].unit, SIZE, stdin);
list->itemList[editItemNumber].unit[strlen(list->itemList[editItemNumber].unit) - 1] = '\0'; break;
default: break;
}
}
void itemDeleter(struct ShoppingList* list, int deleteThis) {
for (int i = deleteThis - 1; i < list->length; i++) {
list->itemList[i] = list->itemList[i + 1];
}
list->length = list->length - 1;
}
int memoryAllocator(struct ShoppingList** ListInMemory, int length){
struct ShoppingList* temp;
if (length == 0) {
temp = (struct ShoppingList*)calloc(1, sizeof(struct ShoppingList));
}
else {
temp = (struct ShoppingList*)realloc(*ListInMemory, (length + 1) * sizeof(struct ShoppingList));
}
if (temp != NULL) {
printf("A memory error has occured, please try again\n");
return 0;
}
else {
*ListInMemory = temp;
return 1;
}
}
void memoryReturn(struct ShoppingList* list) {
free(list->itemList);
}
No matter what I do or try I can't get the malloc function to return anything else that NULL which gets rejected in the if function. Without the if funktion it gives an error the pointer is a nullptr and crashes.
Most of the changes are in memoryAllocator
Changed the call to memoryAllocator in addItem
memoryAllocator allocates GroceryItem rather than ShoppingList
The other function are removed to be implemented later.
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define SIZE 100
#define CLEAR while(getchar() != '\n');
struct GroceryItem {
char productName[SIZE];
float amount;
char unit[SIZE];
};
struct ShoppingList{
struct GroceryItem *itemList;
int length;
};
void enterProductName(struct ShoppingList* plist);
void enterUnit(struct ShoppingList* plist);
void negativeCheck(struct ShoppingList* plist);
int memoryAllocator(struct ShoppingList* ListInMemory, int length);
void memoryReturn(struct ShoppingList* list);
void addItem(struct ShoppingList* list) {
int error = 0;
error = memoryAllocator(list, list->length);
if (error == 0)
return;
enterProductName(list);
negativeCheck(list);
enterUnit(list);
printf("This item has been added!\n\n");
return;
}
void printList(struct ShoppingList *list) {
if (list->length == 0) {
printf("\nYour shoppinglist is empty! Start by adding an item.");
return;
}
printf("\nYour shopping list\n\n");
printf("Nr Item\t\t Ammount\tUnit\n");
for (int i = 0; i < list->length; i++) {
printf("%d. %-20s", i+1, list->itemList[i].productName);
printf("%-8.1f %s\n", list->itemList[i].amount, list->itemList[i].unit);
}
}
void enterProductName(struct ShoppingList* plist) {
int item = plist->length - 1;
printf("Enter item name: ");
fgets(plist->itemList[item].productName, SIZE, stdin);
plist->itemList[item].productName[strlen(plist->itemList[item].productName) - 1] = '\0';
}
void enterUnit(struct ShoppingList* plist) {
int item = plist->length - 1;
printf("Enter the unit (e.g. kg): ");
fgets(plist->itemList[item].unit, SIZE, stdin);
plist->itemList[item].unit[strlen(plist->itemList[item].unit) - 1] = '\0';
}
void negativeCheck(struct ShoppingList* plist) {
int item = plist->length - 1;
int ammountNegative = 1;
do {
printf("Enter ammount: ");
scanf("%f", &plist->itemList[item].amount); CLEAR
if (plist->itemList[item].amount < 0) {
printf("\nYou can only enter positive numbers!\n");
ammountNegative = 1;
}
else
ammountNegative = 0;
} while (ammountNegative != 0);
}
int memoryAllocator(struct ShoppingList* ListInMemory, int length){
struct GroceryItem* temp;
temp = realloc(ListInMemory->itemList, (length + 1) * sizeof *temp);
if (temp == NULL) {
printf("A memory error has occured, please try again\n");
return 0;
}
else {
temp[length].productName[0] = 0;
temp[length].amount = 0.0f;
temp[length].unit[0] = 0;
ListInMemory->itemList = temp;
ListInMemory->length += 1;
return 1;
}
}
void memoryReturn(struct ShoppingList* list) {
free(list->itemList);
}
int main(void)
{
struct ShoppingList shoppingList;
shoppingList.length = 0; // The shopping list is empty at the start
shoppingList.itemList = NULL;
int option;
do
{
printf("\n\nWelcome to the shopping list manager!\n");
printf("=====================================\n\n");
printf("1. Add an item\n");
printf("2. Display the shopping list\n");
printf("3. Remove an item\n");
printf("4. Change an item\n");
printf("5. Save list\n");
printf("6. Load list\n");
printf("7. Exit\n");
printf("What do you want to do? ");
scanf("%d", &option); CLEAR
switch (option)
{
case 1: addItem(&shoppingList); break;
case 2: printList(&shoppingList); break;
case 3: break;
case 4: break;
case 5: break;
case 6: break;
case 7: memoryReturn(&shoppingList); break;
default:
printf("Please enter a number between 1 and 7");
}
} while (option != 7);
return 0;
}

How do i send a string to another function using c?

i am trying to send a string that is "genrecode" back to my main function from the my other function known as char Vote. At first, i used the 'int' data type for the variable "genreCode" since its just integers but i wanted to see if i can send it as a string. How do i do that?
#include <stdio.h>
#include<string.h>
void View_Genre();
char Vote();
void View_Result(int, int, int);
void Exit(int, int , int);
int main ()
{
int option;
char genreCode[2];
int rock=1;
int pop=1;
int country=1;
int Trock=0;
int Tcountry=0;
int Tpop=0;
printf("WELCOME TO MUSIC GENRE VOTING SYSTEM\n");
printf("View Genre\n");
printf("Vote\n");
printf("View Result\n");
printf("Exit\n");
do
{
printf("\nInput option : ");
scanf("%d", &option);
switch(option)
{
case 1 : View_Genre();
break;
case 2 : genreCode=Vote();
if(strcmp(genreCode,"11")==0)
{
Trock=Trock+rock;
}
else if(strcmp(genreCode,"22")==0)
{
Tpop=Tpop+pop;
}
else if(strcmp(genreCode,"33")==0)
{
Tcountry=Tcountry+Tpop;
}
break;
case 3 : View_Result(Trock, Tpop, Tcountry);
break;
case 4 :Exit(Trock, Tpop, Tcountry);
}
}while(option==1 || option==2 || option==3);
printf("\nThank you.");
return 0;
}
void View_Genre()
{
printf("GENRE CODE\n");
printf("ROCK 11 \n");
printf("Pop 22 \n");
printf("Country 33 \n\n");
}
char Vote()
{
char genreCode[2];
printf("Enter genre code : ");
scanf("%d", &genreCode);
if(strcmp(genreCode,"11")==0)
{
printf("Your favourite genre is Rock");
}
else if(strcmp(genreCode,"22")==0)
{
printf("Your favourite genre is Pop");
}
else if(strcmp(genreCode,"33")==0)
{
printf("Your favourite genre is Country");
}
return genreCode;
}
void View_Result(int Nrock, int Npop, int Ncountry)
{
printf("GENRE VOTES\n");
printf(" Rock %d \n", Nrock);
printf(" Pop %d \n", Npop);
printf(" Country %d \n", Ncountry);
}
void Exit(int Nrock,int Npop,int Ncountry)
{
char popular[10];
if(Nrock!=0 || Npop!=0 || Ncountry!=0)
{
if(Nrock>Npop)
{
if(Nrock>Ncountry)
{
strcpy(popular,"Rock");
}
else
{
strcpy(popular,"Country");
}
}
else if(Npop>Ncountry)
{
strcpy(popular,"Pop");
}
else
{
strcpy(popular,"Country");
}
printf("The most popular music genre is : %s\n", popular);
}
else
{
printf("\nYou have not vote any genre\n");
}
}
The rest are all correct. I just need to find out how do i send back a string to my main function.
You could do this by allocating space in the heap for your genreCode variable.
//...
#include <stdlib.h>
//...
int main ()
{
// ...
//allocate space for 3 chars in the heap
//the third char stores the string terminator '\0'
char* genreCode = malloc(sizeof(char)*3);
// ...
do
{
//...
switch(option)
{
//...
case 2 : Vote(genreCode);
//...
break;
//...
}
}while(option==1 || option==2 || option==3);
//...
free(genreCode); //Free the allocated memory
return 0;
}
//...
void Vote(char* genreCode)
{
printf("Enter genre code : ");
scanf("%s", genreCode);
//...
}
//...
Reference:
malloc() - Tutorialspoint

Implementing linked list in C

I am trying to implement linked list in C, having options for creation, insertion, deletion and display.
My code is:
#include <stdio.h>
#include <conio.h>
void createFirst(int);
void appendNode(int);
void insertFirst(int);
void insertNode(int,int);
void deleteFirst();
void deleteNode(int);
void display();
struct Node
{
int data;
struct Node *link;
};
typedef struct Node Node;
Node *start = NULL;
int count=0;
void main()
{
int ch;
do
{
printf("\f\n");
printf("1. Create the list \n");
printf("2. Insert an element at any position \n");
printf("3. Delete an element at any position \n");
printf("4. Display the list \n");
printf("5. Quit \n");
printf("Enter your choice : \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int a;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
createFirst(a);
while(1)
{
printf("Do you want to continue[Y/N] : \n");
scanf(" %c",&c);
if(c=='Y' || c=='y')
{
printf("Enter the data : \n");
scanf("%d",&a);
appendNode(a);
}
else if(c=='N' || c=='n')
{
break;
}
else
{
continue;
}
}
break;
}
case 2:
{
int a,pos;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
}
break;
}
case 3:
{
int pos;
char c;
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
}
break;
}
case 4:
{
display();
break;
}
case 5:
{
return;
}
default:
{
printf("Invalid choice \n");
break;
}
}
}while(ch!=5);
}
void createFirst(int d)
{
Node newnode = {d,NULL};
start = &newnode;
count++;
}
void appendNode(int d)
{
Node temp = *start;
while(temp.link != NULL)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
temp.link = &newnode;
count++;
}
void insertFirst(int d)
{
Node newnode = {d,NULL};
newnode.link = start;
start = &newnode;
count++;
}
void insertNode(int n,int d)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
newnode.link = temp.link;
temp.link = &newnode;
}
void deleteFirst()
{
if(start != NULL)
{
printf("Deleted element : %d \n",(*start).data);
start = (*start).link;
count--;
}
else
{
printf("Underflow \n");
}
}
void deleteNode(int n)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
printf("Deleted node : %d",temp.link->data);
temp = *(temp.link->link);
count--;
}
void display()
{
if(start == NULL)
{
printf("The list is empty \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<=count;i++)
{
printf("%d ",temp.data);
temp = *temp.link;
}
}
But:
Whenever the control is going to appendNode function, the program terminates somehow.
After only creating the first node, if i go to display, it is printing some garbage value.
Please somebody help.
Your problem is on the line (inside of appendNode) which contains this: Node temp = *start;. Don't do it that way. Do it this way:
Node *temp = start;
Change the following pointer notations to accomodate this change. Like change the dot operators to the -> operator. Here's the rest of the function:
while(temp->link != NULL)
{
temp = temp->link;
}
Node *newnode = malloc (sizeof(struct Node));
newnode->data = 0;
newnode->link = NULL;
temp->link = newnode;
count++;

Why does the recursion mess up, and end up getting into an infinite loop?

Can anyone tell why my recursion is messing up? THANK YOUUUUU
This is stack in C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
struct node
{
char stdNum[12], stdName[24], CnY[10];
float gwa;
struct node *link;
};
// Initialized Functions
void createStck();
void traverseStck();
void recursion();
void push();
// Declare Globally to be used in other functions
struct node *TOP = NULL;
struct node *tempTop = NULL, *tempNode = NULL;
bool tempTopExist = false, travesalDone = false, pushTemptoTop = false, firstIteration = false;
struct node *ptr = NULL;
MENU
int main()
{
system("CLS");
int input;
do
{
printf("1 - Creation of Nodes in Stack\n");
printf("2 - Traversal of Nodes in Stack\n");
printf("3 - Addition of Nodes in Stack\n");
printf("4 - Deletion of Nodes in Stack\n\n");
printf("Choice: ");
scanf("%d", &input);
} while (input > 4 || input < 1);
switch (input)
{
case 1:
createStck();
break;
case 2:
traverseStck(TOP);
break;
}
return 0;
}
Creation of Stack
void createStck()
{
struct node *PushNode = NULL;
PushNode = malloc(sizeof(struct node));
PushNode->link = NULL;
TOP = PushNode;
char resp, temp;
do
{
printf("Student Number : ");
scanf("%s", &PushNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->CnY);
printf("GWA : ");
scanf("%f", &PushNode->gwa);
printf("\n(ALERT) Add another node [Y/N]? ");
scanf(" %c", &resp);
if (resp == 'Y' || resp == 'y')
{
printf("\n");
PushNode = malloc(sizeof(struct node));
PushNode->link = TOP;
TOP = PushNode;
}
} while (resp == 'Y' || resp == 'y');
PushNode = NULL;
main();
}
Traversing the stack while also pushing each value into a temporary storage and finally getting it back from that temporary storage
if input = 1 2 3
stack will be 3 2 1
traversing will be 3 2 1
pushing each will end up 1 2 3 (last in last out)
the problem is when I push it back (last in last out) using recursion
void traverseStck(struct node *TOP)
{
struct node *popNode = NULL;
popNode = TOP;
if (popNode == NULL)
{
printf("The Stack is empty!");
}
else
{
do
{
printf("%s\n", TOP->stdNum);
printf("%s\n", TOP->stdName);
printf("%s\n", TOP->CnY);
printf("%f\n\n", TOP->gwa);
TOP = TOP->link;
popNode->link = NULL;
push(popNode);
tempTopExist = true;
popNode = TOP;
} while (TOP != NULL);
travesalDone = true;
push(tempTop);
getch();
main();
}
}
void recursion(struct node *poppedNode)
{
if (poppedNode == NULL)
{
tempTopExist = false;
tempTop = NULL;
tempNode = NULL;
travesalDone = false;
}
else
{
if (firstIteration == false)
{
firstIteration = true;
TOP = poppedNode;
TOP->link = NULL;
recursion(poppedNode->link);
}
else
{
tempNode = poppedNode;
tempNode->link = TOP;
TOP = tempNode;
recursion(poppedNode->link);
}
}
}
void push(struct node *poppedNode)
{
if (travesalDone == false)
{
if (tempTopExist == false)
tempTop = poppedNode;
if (tempTopExist == true)
{
tempNode = poppedNode;
tempNode->link = tempTop;
tempTop = tempNode;
}
}
if (travesalDone == true)
{
tempNode = NULL;
recursion(poppedNode);
firstIteration = false;
}
}
I did not use recursion and just made a copy to be traversed making the original stack untouched.
Solved. Thank you guys
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
struct node
{
char stdNum[12], stdName[24], CnY[10];
float gwa;
struct node *link;
};
// Initialized Functions to avoid errors
void createStck();
void traverseStck();
void addStck();
void delStck();
void endProg();
// Declared Globally to be used in other functions
struct node *TOP = NULL, *ptr = NULL;
// Check if Stack is already created
bool stackCreated = false;
int main()
{
system("CLS");
int input;
do
{
system("CLS");
printf("1 - Creation of Nodes in Stack\n");
printf("2 - Traversal of Nodes in Stack\n");
printf("3 - Addition of Nodes in Stack\n");
printf("4 - Deletion of Nodes in Stack\n");
printf("5 - End Stack Program\n\n");
printf("Choice: ");
scanf("%d", &input);
} while (input > 5 || input < 1);
switch (input)
{
case 1:
createStck();
break;
case 2:
traverseStck();
break;
case 3:
addStck();
break;
case 4:
delStck();
break;
case 5:
endProg();
break;
}
return 0;
}
void createStck()
{
system("CLS");
if (!stackCreated)
{
struct node *PushNode = NULL;
PushNode = malloc(sizeof(struct node));
PushNode->link = NULL;
TOP = PushNode;
char resp, temp;
do
{
printf("Student Number : ");
scanf("%s", &PushNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->CnY);
printf("GWA : ");
scanf("%f", &PushNode->gwa);
printf("\n(ALERT) Add another node [Y/N]? ");
scanf(" %c", &resp);
if (resp == 'Y' || resp == 'y')
{
printf("\n");
PushNode = malloc(sizeof(struct node));
PushNode->link = TOP;
TOP = PushNode;
}
} while (resp == 'Y' || resp == 'y');
PushNode = NULL;
stackCreated = true;
main();
}
else
{
char choice;
printf("(ALERT) The stack already created!\n");
printf("Do you want to create a stack? [Y/N]: ");
scanf(" %c", &choice);
(choice == 'Y' || choice == 'y') ? (stackCreated = false, createStck()) : (printf("\n(ALERT) You will now be redirected to the main menu!"), sleep(2), main());
}
}
void traverseStck()
{
system("CLS");
ptr = TOP;
if (ptr == NULL)
{
printf("(ALERT) The Stack is empty!, please create a stack before traversing");
sleep(2);
main();
}
else
{
do
{
printf("Student Number : %s\n", ptr->stdNum);
printf("Student Number : %s\n", ptr->stdName);
printf("Course and Year : %s\n", ptr->CnY);
printf("GWA : %f\n\n", ptr->gwa);
ptr = ptr->link;
} while (ptr != NULL);
printf("(ALERT) Press any key to continue...");
getch();
main();
}
}
void addStck()
{
system("CLS");
if (TOP == NULL)
{
char choice;
printf("(ALERT) The stack is empty\n");
printf("Do you want to create a stack? [Y/N]: ");
scanf(" %c", &choice);
(choice == 'Y' || choice == 'y') ? createStck() : (printf("\n(ALERT) You will now be redirected to the main menu!"), sleep(2), main());
}
else
{
struct node *addNode = NULL;
addNode = malloc(sizeof(struct node));
char temp;
printf("Student Number : ");
scanf("%s", &addNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", addNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", addNode->CnY);
printf("GWA : ");
scanf("%f", &addNode->gwa);
addNode->link = TOP;
TOP = addNode;
addNode = NULL;
printf("\n(SUCCESS) New Node added on the top of the stack!");
sleep(2);
main();
}
}
void delStck()
{
system("CLS");
if (TOP == NULL)
{
printf("(ALERT) The Stack is empty!, cannot delete if stack does not exist!\n");
}
else if (TOP->link == NULL)
{
TOP = NULL;
printf("(SUCCESS) The stack has been deleted!");
stackCreated = false;
}
else
{
ptr = TOP;
ptr = ptr->link;
TOP = ptr;
ptr = NULL;
printf("(SUCCESS) The top stack has been deleted!");
}
sleep(2);
main();
}
void endProg()
{
system("CLS");
printf("Thank you for using my program - Ace :)");
sleep(2);
exit(1);
}

Access a field of a structure that is within the union of it

This program must handle data that represents the products used in the factory. It is desired that the product represents the following characteristics: Code, description unit of measure, and price; In turn, if the product is imported you want to know the origin of the product, while if it is purchased in the square you want to know the name of the provider's phone number.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <stdbool.h>
#include <winsock.h>
void clrscr();
typedef enum {IMPORTED, LOCAL} type;
typedef struct
{
int code;
char description [20];
char MeasureUnit [5];
float price;
type discriminant;
union
{
char origin [20];
char destination [20];
int telephone;
} impoExpo;
} Product;
//this procedure fails
void loadProduct (Product *p)
{
printf("\nEnter the code:");
scanf("%d",&Product.code); //<-error: expected expression before 'Product'
fflush(stdin);
printf("\nEnter the description:");
scanf("%s",Product.description);
printf("Indicate the unit of measure:");
scanf("%s",Product.MeasureUnit);
printf("Enter the price:");
scanf("%f",&Product.price);
int i;
printf("\nInsert 1 if imported");
scanf("%d", &i);
if(i == 1)
{
p->discriminant = IMPORTED;
}
else
{
p->discriminant = LOCAL;
}
if(p->discriminant == IMPORTED)
{
printf("\nEnter source: ");
gets(p->impoExpo.origin);
}
else
{
printf("\nEnter the phone");
scanf("%d", &p->impoExpo.telephone);
}
}
//it is also
void showProduct (Product p)
{
printf("\nCode: %d", p.code); //<----- error: request for member 'code' in something not a structure or union
printf("\nDescription");
printf("%s", p.description);
printf("\nMeasurement unit:");
printf("%s", p.MeasureUnit);
printf("\nPrice:% .2f", p.price);
printf("\nType:");
if (p.discriminant == IMPORTED)
{
printf("Imported:");
printf("\nOrigin: %s", p.impoExpo.origin);
printf("%s", p.impoExpo.origin);
}
else
{
printf("Local:");
printf("\nTelephone: %d", p.impoExpo.telephone);
}
}
//this one also
bool areequal (Product p1, Product p2)
{
bool equal = false;
if ((p1.code == p2.code) && (p1.description == p2.description))
{
if ((p1.MeasureUnit == p2.MeasureUnit) && (p1.price == p2.price))
{
if (p1.discriminant == p2.discriminant)
{
if (p1.discriminant == IMPORTED)
{
if (p1.impoExpo.origin == p2.impoExpo.origin)
{
equal = true;
}
}
else
{
if (p1.impoExpo.telephone == p2.impoExpo.telephone)
{
equal = true;
}
}
}
}
}
return equal;
}
//this función ok
void copy (Product * const destination, const Product * const origin)
{
destination->code = origin->code;
(*destination->description) = (*origin->description);
(*destination->MeasureUnit) = (*origin->MeasureUnit);
destination->price = origin->price;
destination->discriminant = origin->discriminant;
if(destination->discriminant == IMPORTED)
(*destination->impoExpo.origin) = (*origin->impoExpo.origin);
else
destination->impoExpo.telephone = origin->impoExpo.telephone;
}
//and the latter also
int main ()
{
int option;
do
{
clrscr();
printf("Welcome to the program\n");
printf("Enter an option\n");
printf("1. Load a product\n");
printf("2. Show product\n");
printf("3. Check if two products are the same\n");
printf("0. Exit");
printf("Enter the option, and press ENTER");
scanf("%d",&option);
switch (option)
{
case 1:
loadProduct(&p);
getch();
break;
case 2:
showProduct(p);
getch();
break;
case 3:
printf("Enter the name of the product 1");
scanf("%d",&p1);
printf("Enter the name of the product 2");
scanf("%d",&p2);
printf("% d",areequal (p1, p2));
getch();
break;
}
} while (option != 0);
getch();
return 0;
}
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
Product is a pointer, so you have to access its members using the arrow notation:
scanf("%d",&p->code); //<-error: expected expression before 'Product'

Resources