pointers in 2D array

closed account (4ET0pfjN)
Hi, is this one way to 'reset' a 2D array via pointers:

1
2
for (p = &a[O]; p < &a[NUM_ROWS]; p++)
 (*p)[i] = 0;


this is directly from a C book, but what's i, I think it's a typo...

so it shouldn't just be *p = 0 as in a 1-D array since I understand that C/C++ treats a 2D (or any multidimensional array) as a 1-D array with pointers to a subarray of size column.
Last edited on
The [i] seems like a typo for a 1D array, but for a 2D array you would need to iterate over each sub-object and set to '0' individually. I am unsure if looking at the address of a[NUM ROWS] will ever cause an error, as that index is out of bounds for the 'a' array - anyone else know for sure?

Also, I am not a fan of this, as p and a need not be of the same type for the above code to work. Consider the example:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>

using namespace std;

struct Parent
{
	int a;
	int b;

	Parent & operator=(int n)
	{ 
		a = b = n; 
		return *this;
	}
};

struct Child : public Parent
{
	int c;

	Child & operator=(int n)
	{ 
		a = b = c = n; 
		return *this;
	}
};

int main()
{
	const int ARRAY_SIZE = 9;
	Child arr[ARRAY_SIZE];
	for (int i = 0; i < ARRAY_SIZE; i++)
	{
		cout << "Address at " << i << " is: " << &arr[i] << endl;
	}

	
	cout << endl;

	for (Parent * p = &arr[0]; p < &arr[ARRAY_SIZE]; p++)
	{
		cout << "Address is: " << p << endl;
		(*p) = 0; // This will cause some issues, depending on the sizes of Parent and Child, and your array size
	}

	return 0;
}


Note that visual studio gives me the error that 'Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.' after the application exits, but nothing during compilation. This is because we are setting what we think is a Parent to '0', but the pointer is actually pointing to the middle of a Child object. Change ARRAY_SIZE to 1, and you'll get the same error, but it will be easier to visualize. If we use an even ARRAY_SIZE though, we get no error, making it a potentially more difficult error to reproduce.
Last edited on
Topic archived. No new replies allowed.