More Pointers Flashcards
in general how does C store two-dimensional arrays?
Draw it.
define NUM_ROWS 3
How would you code the initialization of all elements in the following array to zero using the property of how 2d arrays are stored in memory?
int a[NUM_ROWS][NUM_COLS];
How would you use a pointer variable p to process the elements in just one row or a 2d array?
Explain why a[i] is a pointer to the first element in row i?
Code a loop that clears row i of the array a
find_largest finds the largetst element of a one-dimensional array, how would we use find_largest to determine the largest element in row i of a 2d array a?
largest = find_largest(___, ____);
How would you code a loop that clears column i of the array a?
In the code:
int a[NUM_ROWS][NUM_COLS];
where does a point? Explain how this works
Pointers to Pointers
What does the attached code do?
It is passed a pointer and returns a pointer to a new node. This new node can be used to add to the current list.
If the attached code modified the list directy instead of return a new node, what would the affect be?
In the attached code, modifying add_to_list so that it assigns new_node to list instead of returning new_node doesn’t work, why?
How would you modify the code so that it assigns new_node inside the function?
Why:
At the point of the call, first is copied into list, if the function changes the value of list, making it point to the new node, first is not affected.
How to fix
- When the new version of add_to_list is called, the first argument will be the address of first:
- add_to_list(&first, 10);
- since list is assigned the address of first, we can use *list as an alias for first.
- In particular, assigning new_node to *list will modify first
How do you use pointers to pointers to dynamically create multidimensional arrays?