Code:
#include <stdio.h>
#include <stdlib.h>
struct listNode {
char data;
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char);
char delete_me(LISTNODEPTR *, char);
int isEmpty(LISTNODEPTR);
void printList(LISTNODEPTR);
void instructions(void);
int main(int argc, char* argv[])
{
LISTNODEPTR startPtr = NULL;
int choice;
char item;
instructions(); /*display the menu*/
printf("? ");
scanf("%d", &choice);
while (choice != 3) {
switch (choice) {
case 1:
printf("Enter a character ");
scanf("\n%c", &item);
insert(&startPtr, item);
printList(startPtr);
break;
case 2:
if (!isEmpty(startPtr)) {
printf("Enter character to be deleted: ");
scanf("\n%c", &item);
if (delete_me(&startPtr, item)) {
printf("%c deleted.\n", item);
printList(startPtr);
}
else
printf("%c not found. \n\n", item);
}
else
printf("List is empty.\n\n");
break;
default:
printf("Invalid choice.\n\n");
instructions();
break;
}
printf("? ");
scanf("%d", &choice);
}
printf("End of run.\n");
return 0;
}
/*Print the instructions*/
void instructions(void)
{
printf("Enter your choice:\n"
" 1 to insert an element into the list.\n"
" 2 to delete an element from the list.\n"
" 3 to end.\n");
}
/*Insert a new value into the list in sorted order*/
void insert(LISTNODEPTR *sPtr, char value)
{
LISTNODEPTR newPtr, previousPtr, currentPtr;
newPtr = (LISTNODEPTR)malloc(sizeof(LISTNODE));
if (newPtr != NULL) {
newPtr->data = value;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = *sPtr;
while (currentPtr != NULL && value > currentPtr->data) {
previousPtr = currentPtr; /*walk to...*/
currentPtr = currentPtr->nextPtr;/*...next node*/
}
if (previousPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else {
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf("%c not inserted. No memory available.\n", value);
}
It's from a textbook I'm using to learn C. The 3 different lines I bolded are where my questions lay. The startPtr is a pointer variable that points to the listNode structure. How come the insert and delete functions use the (&) and the printList function does not? I figured since startPtr is a pointer then the (&) would cause the function to use the address of the pointer variable for insert and delete and without it the printList would receive the address of what the pointer variable points to.
Thanks for help ahead of time!