Reputation: 462
I am passing a double pointer to a function. The function reads data from a file into a linked list. I set CircuitData as the pointer to the first node. After I called the function and want to use CircuitData it is empty. Why does it not return the address of the first node(&newPtr)?
ListNodeType **CircuitData;
int numEl = 0;
int numNodes = 0;
CircuitData = NULL;
ReadFile(CircuitData, &numEl, &numNodes);
printf("%p", CircuitData);
Part of the ReadFile function that I'm calling:
void ReadFile(ListNodeType **CircuitData, int *numEl, int *numNodes){
*numEl = 0;
*numNodes = 0;
ListNodeType *newPtr, *tempPtr;
newPtr = malloc(sizeof(ListNodeType));
CircuitData = &newPtr;
newPtr->nextPtr = NULL;
Upvotes: 0
Views: 170
Reputation: 6050
Define CircuitData as (ListNodeType *), and in function ReadFile, pass &CircuitData
Upvotes: 0
Reputation: 212959
The calling code needs to be like this:
ListNodeType *CircuitData = NULL;
ReadFile(&CircuitData, &numEl, &numNodes);
Upvotes: 0
Reputation: 21213
Remember that values are passed by copy in C. Thus, this assignment inside ReadFile
:
CircuitData = &newPtr;
Will not be propagated to the caller. I think that you wanted this instead:
*CircuitData = newPtr;
For this to work, CircuitData
must point to a valid memory location, don't initialize it to NULL
. You might want to do this instead:
ListNodeType *CircuitData;
And then call the function like this:
ReadFile(ListNodeType &CircuitData, ...)
Upvotes: 1
Reputation: 687
First, the declared type of CircuitData
should be a pointer:
ListNodeType* CircuitData;
To set the address stored in CircuitData
(inside the ReadFile function) you would write
*CircuitData = newPtr;
This sets the data at the address CircuitData
to the address stored in newPtr
, which is what you want to do.
You also need to properly pass the address of the CircuitData pointer to the ReadFile function by calling
ReadFile(&CircuitData, ...)
Upvotes: 2