I have the following code. I know that is wrong, but the thing is that I dont get why. Below I explain my doubts.
#include <stdio.h>
struct mychar {
char value;
struct mychar *nextPtr;
};
typedef struct mychar Mychar;
void insert(Mychar **, char ); // line 19
void printlist(Mychar **);
int main(){
Mychar *startPtr = NULL;
insert(&startPtr, 'b');
printlist(&startPtr);
}
void insert(Mychar **sPtr, char myvalue){
Mychar *newlinkPtr = calloc(1, sizeof(Mychar));
if (**sPtr == NULL){ // if I put two ** I get errors
newlinkPtr->value = myvalue;
newlinkPtr->nextPtr = **sPtr; // same here
**sPtr = newlinkPtr; // same here
}
}
void printlist(Mychar **startPtr){
printf("%c\n", *startPtr->value); // get error
}
Here are the errors:
liste_collegate.c:29:13: error: invalid operands to binary expression ('Mychar' (aka 'struct mychar') and 'void *')
if (**sPtr == NULL){
~~~~~~ ^ ~~~~
liste_collegate.c:31:23: error: assigning to 'struct mychar *' from incompatible type 'Mychar' (aka 'struct mychar'); remove *
newlinkPtr->nextPtr = **sPtr;
^ ~~~~~~
liste_collegate.c:32:10: error: assigning to 'Mychar' (aka 'struct mychar') from incompatible type 'Mychar *' (aka 'struct mychar *'); dereference with *
**sPtr = newlinkPtr;
^ ~~~~~~~~~~
*
liste_collegate.c:38:26: error: member reference base type 'Mychar *' (aka 'struct mychar *') is not a structure or union
printf("%c\n", *startPtr->value);
My doubts:
- Why if in the arguments of
insertfunction I write**sPtr, then in the if block I have to use*sPtr, otherwise it gives me error? Shoudn't**sPtrbe equal to NULL, since I have put NULL value inside it in the main? In themain(), when I callinsertin line 19, I send there the address & ofstartPtr, so to access to its value NULL in theinsertfunction, I should put a*to actually reach the pointer, and another*to actually reach the NULL value.. - In
printlistfunction, pretty much the same doubts of before. If I "send" toprintlistthe address of the first pointer of the linked list, to actually access the first structure, shouldn't I dereferenciate to actually reach the struct address, and then dereferenciate again with->to control the pointer of that structure to get "value"?