OK I've been working on this code for about a day and a half now and figured I would have figured out why it's not working.
1 - Says I'm passing arguments to a parameter (but executes fine)
2 - Only pushes the first letter of my char*
to the stack and not the whole string
#include <stdio.h>
#include <stdlib.h> //malloc and free
#include <limits.h>
#include <ctype.h>
#include <string.h>
char* getMooki();
void push(char* val, char* val2, int a);
void printStack();
void error(char* msg);
typedef struct node{
char* data;
char* date;
int p_price;
struct node *pNext;
}node;
node *pTop = NULL;
int main(int charc, char* argv[]){
int pushVal = 2;
push("Light","Best", 1);
printStack();
push("Moon","Good", 2);
printStack();
char* good;
good = getMooki();
push(&good,"tada", 3);
printStack();
good = getMooki();
push(&good,"work please", 4);
printStack();
}
void push(char* val, char* val2, int a){
if(pTop == NULL){
pTop = malloc(sizeof(node));
pTop -> data = val;
pTop -> date = val2;
pTop -> p_price = a;
pTop -> pNext = NULL;
}else{
node *pNew = malloc(sizeof(node));
pNew -> data = val;
pNew -> date = val2;
pNew -> p_price = a;
pNew -> pNext = pTop;
pTop = pNew;
}
}
void printStack() {
//get temporary pointer:
node *pTemp = pTop;
if (pTemp == NULL) {
error("Print error: stack empty");
return;
}
//walk down the stack, printing each value:
do {
printf("%s ", pTemp -> data);
printf("%s ", pTemp -> date);
printf("%d \n", pTemp -> p_price);
pTemp = pTemp -> pNext;
} while (pTemp != NULL);
printf("\n");
}
void error(char* msg) {
printf("%s\n", msg);
}
char* getMooki(){
char* input;
printf("Enter your string: ");
scanf("%s", &input);
return input;
}
OK i got the above code working some what.... I know I'm having a memory/pointer issue and I'm having trouble finding related documents to what I'm trying to do since it involves passing a char* in C this is what happens when I run the above code
1 - when I pass &good in to my push function for the stack if I do not pass it as an address (&) i get a segmentation error after I enter my string and hit enter. If i leave the & it will pass and push the new data in to the stack.
2- Problem when I ask for a second string to push in to the stack it changes the data in the previous node and the node in the stack.
Logically I'm passing the same address to the stack so the node's data would naturally point to whatever the new data is that was given to good. But if i don't pass it as an address I get a segmentation error 11
Sorry for noob questions but I've spent a couple days now since getting this to work of digging through forums and youtube videos. Writing it on paper and etc.