J
Jonathan Mcdougall
let's say i have a 2D array, how would i access it with a pointer?
The same as an int :
int x = 5;
f(x);
// takes an int
void f(int i)
{
i = 2;
}
The reason for which 'i' is of type 'int' is because 'x' is of type
int.
Now if 'x' is of type 'int[2][2]', well 'i' will be too :
void f(int i[2][2])
{
i[0][0] = 4;
}
But if you allocated the array with new, you probably did something
like
int size_1 = 2;
int size_2 = 2;
int **x = new int*[size_1]
for ( int i = 0; i<size_1; ++i)
x = new int[size_2];
Since 'x' is now of type 'int**', that is what 'i' will be :
void f(int **i)
{
i[0][0] = 4;
}
The 'problem' with that is now you have no idea about the bounds of
'i'. You have two solutions. Either you pass the information too :
void f(int **i, int size_1, int size_2)
{
}
or you use something like the zero-terminated c-style string and
always set the last element to a given value which means end-of-array.
But know that arrays are always passed by address, that is, modifying
its value in f() will modify 'x' too.
Jonathan
int x [2][2];
func(x);
void func(int *x) {
//i want to fill it with a number, like 1
}
The same as an int :
int x = 5;
f(x);
// takes an int
void f(int i)
{
i = 2;
}
The reason for which 'i' is of type 'int' is because 'x' is of type
int.
Now if 'x' is of type 'int[2][2]', well 'i' will be too :
void f(int i[2][2])
{
i[0][0] = 4;
}
But if you allocated the array with new, you probably did something
like
int size_1 = 2;
int size_2 = 2;
int **x = new int*[size_1]
for ( int i = 0; i<size_1; ++i)
x = new int[size_2];
Since 'x' is now of type 'int**', that is what 'i' will be :
void f(int **i)
{
i[0][0] = 4;
}
The 'problem' with that is now you have no idea about the bounds of
'i'. You have two solutions. Either you pass the information too :
void f(int **i, int size_1, int size_2)
{
}
or you use something like the zero-terminated c-style string and
always set the last element to a given value which means end-of-array.
But know that arrays are always passed by address, that is, modifying
its value in f() will modify 'x' too.
Jonathan