Reputation: 85
I have this piece of code which will (hopefully) become a singly-linked list implementation.
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int d;
struct NODE *next;
};
int addNode(int n, struct NODE **root);
int main(){
struct NODE *root = NULL;
addNode(3, &root);
printf("%i\n", root->d);
getch();
return 0;
}
int addNode(int n, struct NODE **root){
if(*root == NULL){
*root = malloc(sizeof(struct NODE));
*root->d = n;
*root->next = NULL;
return 0;
}
}
When I run it, I get "request for member 'd' in something not a structure or union" inside the addNode function; same with the 'next' part. If instead I change the function to this:
int addNode(int n, struct NODE **root){
struct NODE *temp;
if(*root == NULL){
*root = malloc(sizeof(struct NODE));
temp = *root;
temp->d = n;
temp->next = NULL;
return 0;
}
}
it works just fine. My question is; why do I have to create temp? As I understand it, in the first version of the code I am passing a pointer to root, so that there should be no 'pass by reference' issues, and it should not have problems running... What's the mistake?
Upvotes: 0
Views: 130
Reputation: 24895
Please refer to the Operator Precedence Table. The ->
operator has a higher precedence than the *
(dereference) operator, which is the reason for your error.
*root->d is interpreted as *(root->d) instead of (*root)->d due to operator precedence.
Upvotes: 0
Reputation: 45173
Operator precedence.
*root->d = n;
is parsed as
*(root->d) = n;
But you want
(*root)->d = n;
Upvotes: 1
Reputation: 31952
(*root)->d = n;
(*root)->next = NULL;
Its an operator precedence problem. Using ()
will fix it.
Upvotes: 3