All,
I'm hoping you can help me here. I have written a small program for a class to convert decimal to binary and the program itself works, however, I am storing the binary bits in a stack that is in a header file (which I have used successfully before). It appears to push the bits to the stack just fine, however, when I use the printStack function I get a segmentation fault.
Here is the stack.h header file:
Code:
#include <stdlib.h>
#include <stdio.h>
struct stackNode {
int data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
void push( StackNodePtr *topPtr, int info );
int pop( StackNodePtr *topPtr );
void printStack( StackNodePtr currentPtr );
void push( StackNodePtr *topPtr, int info )
{
StackNodePtr newPtr;
newPtr = malloc( sizeof( StackNode ) );
if ( newPtr != NULL )
{
newPtr->data = info;
newPtr->nextPtr = *topPtr;
*topPtr = newPtr;
}
else
{ /* no space available */
printf( "%d not inserted. No memory available.\n", info );
}
}
int pop( StackNodePtr *topPtr )
{
if (*topPtr != NULL)
{
StackNodePtr tempPtr;
int popValue;
tempPtr = *topPtr;
popValue = ( *topPtr )->data;
*topPtr = ( *topPtr )->nextPtr;
free( tempPtr );
return popValue;
}
else
{
printf("The list is empty\n");
}
}
void printStack( StackNodePtr currentPtr )
{
/* if stack is empty */
if ( currentPtr == NULL )
{
printf( "The stack is empty.\n\n" );
}
else
{
while ( currentPtr != NULL )
{
printf( "%d\n", currentPtr->data );
currentPtr = currentPtr->nextPtr;
}
printf( "\n" );
}
}
And here is the main program that does the conversion:
Code:
#include <stdio.h>
#include "stack.h"
int binary (int x);
int main()
{
int choice = 0;
printf("\nPlease enter the decimal number for conversion: ");
scanf("%d", &choice);
int answer = binary(choice);
}
int binary (int x)
{
StackNodePtr Head;
//base case
if (x > 0)
{
//recursive step
push(&Head, x%2);
return binary (x/2);
}
else
{
printStack(Head);
return 0;
}
}
Anything anyone can point out to help me?
Marc
P.S. one other thing of note, whenever I try to modify the printStack function, that function then seems to not work at all.
Thanks
Marc