Reputation:
Having this snippet
int main() {
char *obstacles[3*3]
char map[3][3] = {'D','*',' ',' ',' ',' ','*',' ',' '};
int k = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (map[i][j] == '*')
obstacles[k++] = &map[i][j];
}
}
return 0;
}
Leads to me to this situation:
How do I shrink this array to a k
-cells array?
Upvotes: 0
Views: 131
Reputation: 69367
If your array is declared with a fixed size, there's nothing you can do about it. Its size is chosen at compile time and you have no way of modifying that when the program runs. What you can do however is to use malloc()
and realloc()
, if you really wish to do so. I don't really see a good reason to do that though: it's only 9 pointers, you're not going to have any advantage in reducing that.
You can initialize the array as char *obstacles[3*3] = {NULL}
(all cells set to NULL
) and then later stop at the first NULL
cell when scanning it. This is a common way to avoid passing around the size of the array.
Upvotes: 1
Reputation: 224387
You can't change the size of the array. The best you can do is keep track of the number of elements it contains in a separate variable.
Upvotes: 1