I’m new to C, trying to learn it by coding real things instead of isolated and naive book examples. I’m struggling a lot with understanding pointers correctly. My books aren’t really helping.
I’ve got an array of pointers which i’m initializing the following way:
struct Node **cols;
cols = (struct Node *) calloc(N_RESTRICTIONS, sizeof(struct Node *));
// for loop malloc-ing each cols[0..N_RESTRICTIONS] here
Which seems ok. I need another variable, say upper_nodes, which initially points to the same nodes as cols, but that’ll gonna be changing as the algorithm evolves, while cols does not change. I tried:
struct Node **upper_nodes;
*upper_nodes = *cols;
What i’m expecting is: upper_nodes address is not the same as col’s (they’re different variables), but as the first pointed value in each one is the same due to the assignment, i now can index upper_nodes[i] just like i did with cols, and reassign it without affecting what cols[i] points to.
This isn’t what’s happening, i’m getting a segmentation fault and in the debugger i see the first value in both vars points to the same item, but after that upper_nodes has random values (like non-initialized, i’m sure that’s what happens but i don’t get it).
What i’m not getting here? What’s the way to do this?
Bonus question: I see that the last chunk of code above does the same as:
struct Node **upper_nodes = cols;
I don’t understand this either. I would now expect upper_nodes and cols to have the same address but they haven’t, which seems to say i’m not even understanding how variables work.
>Solution :
Pointers are really what their name implies: They are a thing that points to another thing.
It becomes really clear if you draw it all out on paper:
+------+ +---------+ +------------+------------+-----+
| cols | --> | cols[0] | --> | cols[0][0] | cols[0][1] | ... |
+------+ +---------+ +------------+------------+-----+
| cols[1] |
+---------+
| . |
| . |
| . |
+---------+
Then when you say that you
expect
upper_nodesandcolsto have the same address
If you mean that you expect &upper_nodes to be equal to &cols then that not correct. Drawn out it will look like:
+--------------+ +-------------+
| &upper_nodes | --> | upper_nodes | --\
+--------------+ +-------------+ | +---------+-----+
>--> | cols[0] | ... |
+-------+ +------+ | +---------+-----+
| &cols | --> | cols | ----------------/
+-------+ +------+
So &upper_nodes point to the variable upper_nodes. And &cols point to the variable cols.
And both upper_nodes and cols point to cols[0].
So &upper_nodes != &cols, but upper_nodes == cols.
Note that the above diagram assumes
struct Node **upper_nodes = cols;