Ok, I'm working with using member functions in structures in C, which I've never done before, and I'm stuck. Here's the code:
[code]
typedef struct Node
{
char data;
struct Node* next;
}node,*node_ptr;
typedef struct stack
{
node* head;
int length;
void (*push)(char,node_ptr);
char (*pop)(node_ptr);
}stack,*stack_ptr;
void push(char info,node_ptr head)
{
node_ptr current;
current=(node *)malloc(1);
current->data=info;
current->next=head;
head=current;
}
char pop(node_ptr head)
{
node_ptr current;
char input;
input=head->data;
head=head->next;
free(current);
return(input);
}
[/code]
Now my problem is that I don't want to have to reference a node as a variable to push and pop, I want to use the head of the stack as the only node they will modify. How would I go about doing this?
Comments
C does not really have c++ style member functions -- they are just global functions that can be called at any time anywhere in the program.
Here is one way to solve your proglem, which uses pointer-to-pointer. Also note the change to malloc() in push(), your program was not allocating enough memory for the node structure.
[code]
typedef struct Node
{
char data;
struct Node* next;
}node,*node_ptr;
typedef struct stack
{
node* head;
int length;
void (*push)(char,node_ptr);
char (*pop)(node_ptr);
}stack,*stack_ptr;
void push(char info,node_ptr* head)
{
node_ptr current;
current=(node *)malloc(sizeof(struct Node));
current->data=info;
current->next = 0;
if(*head == 0)
{
*head = current;
}
else
{
// find the tail
node_ptr n = *head;
while(n->next != 0)
n = n->next;
// add node to the end of the list
n->next = current;
}
}
char pop(node_ptr* head)
// removes the head node of the linked list
// in FIFO (first in, first out)
{
node_ptr current;
char input;
if(*head == 0) return 0;
current = *head;
*head = current->next;
input = current->data;
free(current);
return(input);
}
int foo()
{
struct stack stk;
stk.head = 0;
stk.length = 0;
push('A',&stk.head);
pop(&stk.head);
return 0;
}
[/code]
http://globalproganswer.com/materials/95