1. pointers and Arrays
I learned this lesson when I first learned the C language. Here is a simple introduction. Read a paragraphCode:
# DefineSize 10
IntMain (Void)
{
IntA [size], * P, sum;
IntI;
P =;
Sum = 0;
For(I = 0; I <size; I ++)
{
A [I] = I + 1;
}
For(; P <& A [size]; P ++)
{
Sum + = * P;
}
Printf ("% D", Sum );
}
A very simple piece of code is to access array elements through pointers. Here, we only mention & A [size], although a [size] does not exist, when the last element of the array is a [size-1], the C compiler does not check the subscripts out of bounds, that is, a [size] can be accessed, so we can terminate the For Loop in this way.
In addition, access to arrays by pointers or subscripts is focused on access efficiency. In fact, this depends on the specific implementation of different compilers, which is not mentioned in the C standard.
2. pointers and multi-dimensional arrays
I have never understood the C language in college, but it seems easier now.
The two-dimensional array is actually stored as a continuous memory space. Therefore, we can treat the two-dimensional array as a one-dimensional array, as shown in the following code:
# DefineRow 3
# DefineCol 5
IntMain (Void)
{
IntA [row] [col], * P, sum;
IntI, J;
P = & A [0] [0];
Sum = 0;
For(I = 0; I <row; I ++)
{
For(J = 0; j <Col; j ++)
{
A [I] [J] = J + 1;
}
}
While(P <= & A [row-1] [col-1])
{
Sum + = * (p ++ );
}
Printf ("% D", Sum );
}
However, it seems that this process is not readable. For some old compilers, this process is more efficient, but it is no longer advantageous for modern compilers.
Therefore, we should do this in general. We know that for two-dimensional arrays, for example, a [I] [J], in fact, a [0] represents the address of the first element of the first line. Then we can use this to access multi-dimensional array elements:
# DefineRow 3
# DefineCol 5
IntMain (Void)
{
IntA [row] [col], * P, sum;
IntI, J;
Sum = 0;
For(I = 0; I <row; I ++)
{
For(J = 0; j <Col; j ++)
{
A [I] [J] = J + 1;
}
}
For(I = 0; I <row; I ++)
{
For(P = A [I]; P <A [I] + Col; P ++)
{
Sum + = * P;
}
}
Printf ("% D", Sum );
}