I got this from a book i thought i knew pointers already until i saw this..
Compiled with MVC++
4 warnings.. works fine though
Code:#include<stdio.h>
#include<stdlib.h>
// What is this typedef to a pointer for? How does this work?
typedef struct listnode{
int data;
struct listnode *next;
}*Listnode;
void printmenu();
int insert( Listnode *, int );
void printlist( Listnode );
int main()
{
int mode = 0;
Listnode *start = NULL;
int data = 0;
//clrscr();
printmenu();
while( 1 ) {
printf( "\nEnter Command:" );
scanf( "%d", &mode );
if( mode == 1 ){
printf( "\n Enter Data:" );
scanf( "%d", &data );
insert( &start, data ); // I got a warning here
printlist( start );
}
else if( mode == 2 ){
}
else return 0;
}
//getch();
return 0;
}
void printmenu()
{
printf( "\n\n1 - Insert Data\n"
"2 - Delete Data\n"
"3 - Exit Simulation\n\n" );
}
int insert( Listnode *startPtr, int idata )
{
Listnode newPtr, prevPtr, curPtr;
newPtr = malloc( sizeof( Listnode ) );
newPtr->data = idata;
newPtr->next = NULL;
prevPtr = NULL;
curPtr = *startPtr;
while( curPtr != NULL && idata > curPtr->data ){
prevPtr = curPtr;
curPtr = curPtr->next;
}
if( prevPtr == NULL ){
// this part within this bracket is kinda
confusing.. can someone explain this to me please? Lest say its
the first run of the program startPtr is currently pointing at
nothing... newPtr->next will be assign to point at starPtr, thats fine but then
startPtr points to newPtr right? hows that gonna work? Whats this line for?
Or will this make startPtr from main() to point at newPtr
newPtr->next = *startPtr;
*startPtr = newPtr;
}
else{
prevPtr->next = newPtr;
newPtr->next = curPtr;
}
return 0;
}
void printlist( Listnode startPtr )
{
if( startPtr == NULL )
printf( "\n The List is Empty (%d)\n", startPtr->data );
else{
while( startPtr != NULL ){
printf( "-->%d", startPtr->data );
startPtr = startPtr->next;
}
printf( "-->NULL\n" );
}
}