0

I have a two struct, one is linked list.

typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

typedef struct Node{
       struct node next;
       int value;
}Node

if i allocated memory for a node, let say

 Node *node1=malloc( sizeof(struct Node));

And I also allocated memory for a bookmark, let say

 Mark *mark1=malloc( sizeof(struct Mark));

I want to make the pointer nodeyy in the mark1 points to the same thing as node1, how can i do that?

I think that

 mark1->nodeyy=node1;

is definitely wrong.

1
  • 1
    Now that you have edited the code, why do you think mark1->nodeyy = node1 is wrong? Commented Oct 20, 2012 at 7:25

2 Answers 2

1

change the int* in struct Mark to Node*

typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

then you can do

mark -> nodeyy =  (Node *) malloc(sizeof(Node))
Sign up to request clarification or add additional context in comments.

6 Comments

i though mark-> nodeyy just a reference to a node, why we need to allocate memory for a reference? What is the reason we can not just say mark->nodey=node1; ?
ya but mark->nodeyy is an int* in your code and it cannot hold the address of struct Node
sorry, typo , i mean Node *nodeyy;
we can say mark1->people=10, can we say mark1->nodeyy= node1; ? My question: is that the malloc steps necessary?
because node1 is just a type(just like primitive types int,float). you need to create variables of that type and make mark->nodeyy point to that variable.
|
1

its correct now:

You will have to initialize the pointer or point it to an existing variable that you know won't go out-of-scope. BUT since node1 is dynamically allocated, you're just assigning one pointer to another, this creates a sort of reference to the newly allocated memory pointed by node1.

mark1->nodeyy = node1;

After this statement, mark1->nodeyy and node1 point to the memory location returned by the malloc(sizeof(Node)).

1 Comment

sorry, typo , i mean Node *nodeyy;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.