-
typedef structures
typedef Struct node {
char elem;
struct node * next;
} StackType;
typedef StackType * StackPtr;
StackPtr top;
is now StackPtr a type of variable?? and top is a variable of StackPtr type??
i get confused going from
struct node {
int val;
struct node *next;
};
to
typedef struct node{
char elem;
struct node *next;
}StackType;
these two structures are essentially the same thing, right???????
if that is the case, then is the following correct
Code:
correcting errors in this fragment:
void push (StackPtr *top, char p)
{
StackPtr newptr;
newptr = malloc();
newptr.elem = p;
newptr->next = top;
top = newptr;
}
should be changed to
Code:
void push(StackPtr *top, char p)
{
StackPtr newptr;
newptr=malloc(sizeof(StackPtr));
newptr->elem = p;
newptr->next = top;
top = newptr;
}
-
Code:
void push (StackPtr *top, char p)
{
StackPtr newptr;
newptr = malloc();
newptr.elem = p;
newptr->next = top;
top = newptr;
}
This is incorrect. Close, but incorrect. I'll assume you're using pseudo code, in which, this would be correct. It, correctly, would be this:
Code:
void push (StackPtr *top, char p)
{
StackPtr newptr;
newptr = malloc( sizeof( StackType ) );
newPtr->elem = p; /* you're using a pointer, remember */
newptr->next = top;
top = newptr;
}
Yeah. Your second example is correct.
using 'typedef' means you're defining a new variable type. I actually prefer to do this when making my nodes:
Code:
typedef struct node Node;
Node {
Node *n;
int myVar;
};
Nice and clean.
Quzah.
-
Quzah, your sizeof was of StackType, mine was sizeof StackPtr.
Does it make a difference??? Seems it would, now that I think about it, cuz StackType is a structure type and StackPtr is just a variable of that type. Right??
-
Yes, there is a difference.
The difference is like:
x = malloc( sizeof( struct ThisStruct ) );
x = malloc( sizeof( struct ThisStruct* ) );
The first, you're allocating space for the whole structure.
The second, you're only allocating space for a _pointer_ to a structure. Big difference.
Quzah.
-
Instead of using the old, P-style declarations
Code:
// ----p-style----
typedef Struct node {
char elem;
struct node * next;
} StackType;
typedef StackType * StackPtr;
StackPtr top;
Let's do it this way instead-- much more readable--
Code:
typedef Struct node
{
char elem;
struct node *next;
}StackType,*StackPtr;
StackPtr top;
enjoy.