Sorry for such a basic question but I've been searching for an answer and can't find anything as to why this is happening.
Code below compiles with out errors when I go to push my first scanf to get a new char* and push it to the stack I get a segmentation error.
I can by pass the segmentation 11 error by passing &val when I call the push function. push(&val) but when I pass the address like this the new node doesn't store the new information. Example
I ask for string #1 --> Moon
push the value and print the stack
Moon Two One
I ask for a second String --> Work
Print the Stack and this happens
Work Work Two One
So i'm new to C and realize this has something to do with the pointers and passing by reference vs address vs contents(or so my conclusion) Maybe someone can point me in a good direction for pointers and references read I've read several already but I'm not sure why the code below isn't working. So maybe another read that I haven't found yet.
#include <stdio.h> //includes requried.
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
//defining node for stack
typedef struct node{
char *data;
struct node *pNext;
}node;
//defining functions
void push(char* a);
void printStack();
void error(char* msg);
//declaring global variables
node *pTop = NULL; //pointer to top of stack
//main function
int main(int charc, char* argv[]){
char *val;
push("One");
push("Two");
printStack();
printf("Push a new String to the stack: ");
scanf(" %s", val);
push(val);
printStack();
printf("Push a new String to the stack: ");
scanf(" %s", val);
push(val);
printStack();
}
void push(char* a) {
if (pTop == NULL) {
//stack empty, just set pTop to a new node:
pTop = malloc(sizeof(node));
pTop -> data = a;
pTop -> pNext = NULL;
} else {
//make a new node:
node *pNew = malloc(sizeof(node));
pNew -> data = a;
//assign this node's next pointer to the top node:
pNew -> pNext = pTop;
//this node is the new top of stack:
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);
pTemp = pTemp -> pNext;
} while (pTemp != NULL);
printf("\n");
}
void error(char* msg) {
printf("%s\n", msg);
}
void printStack();non-prototype decclarator resp. the function definition. They are not the same. Both are not identical. If not, get a modern C compiler and enable warnings.char val[64]; ... scanf(" %63s", val);...pTop -> data = a;-->pTop -> data = strdup(a);