Initializing Structs in Linked List

Hello, I am building a linked list using structs, and I'm having a problem with the initialization. This is the code I wrote but, I don't know how to make it work.

H file:
1
2
3
4
5
6
7
8
9
10
11
12
13
typedef struct Data
{
	char* Name;
	int iD;
	int age;
} mData;

typedef struct Node
{
	mData* pData;
	Node* pNext;
	Node* pPrev;
} Node;


the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Node intializeNode(Node* n)
{
	n = new Node;
	n -> pData = new mData;
	n -> pData -> iD = 0;
	n -> pData -> age = 0;
	n -> pData -> Name = "Not Set Yet";
	n -> pNext = NULL;
	n -> pPrev = NULL;
	return n;
}

void printNode(const Node* n)
{
	cout<<n->pData->iD<<endl;
	cout<<n->pData->age<<endl;
	cout<<n->pData->Name<<endl;
}

int main()
{
	Node* n = new Node;
	intializeNode(n);
	printNode(n);
	return 0;
}


I guess the problem is that I am using void initializaton, and after the fuction finished everything gone, but I can't think of a way to make it work.
Thanks for all the help!
Hey,
I hope I'm not too late ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//in main you let n point to a new object
Node* n = new Node;

// aaand then
Node intializeNode(Node* n)
{
// the local-n-pointer points here to your object created in main (to the object of main-n-pointer)

	n = new Node; //now the local-n-pointer points to another object
	n -> pData = new mData;
	n -> pData -> iD = 0;
	n -> pData -> age = 0;
	n -> pData -> Name = "Not Set Yet";
	n -> pNext = NULL;
	n -> pPrev = NULL;
// now you assigned all this stuff to the object your local-n-pointer points to
	return n; // I don't know why u return n here (this shouldn't even compile)
//change declaration to "void" and forget the return would be my suggestion
}


Well and then after your "initializeNode(Node)" function finished. Your Node* n from main points to the object you created in "main" not the one you created in the function and assigned all this stuff to.
Thus calling printNode with an unitialized mData* pData isn't working.

(easy fix: just don't create in "initializeNode" a "new Node"
=> n = new Node; <-- remove this line)

Furthermore like mentioned before I don't think initializeNode needs a return value.
Topic archived. No new replies allowed.