|
Evidence that [ ] is an operator:
|
|
|
p [ i ]
where:
p is a reference typed expression
i is an integer typed expression
|
meaning of the [ ] operator:
p [ i ] <===> *(p + i)
|
Note:
|
|
|
int main(int argc, char *argv[])
{
int i;
double* p; // We uses this reference variable to access
// dynamically created array elements
p = calloc(10, sizeof(double) ); // Make double array of 10 elements
for ( i = 0; i < 10; i++ )
p[i] = i; // put value i in array element i
for ( i = 0; i < 10; i++ )
printf("*(p + %d) = %lf, p[i] = %lf\n", i, *(p+i), p[i] );
free(p); // Un-reserve the first array
putchar('\n');
p = calloc(4, sizeof(double) ); // Make a NEW double array of 4 elements
for ( i = 0; i < 4; i++ )
p[i] = i*i; // put value i*i in array element i
for ( i = 0; i < 4; i++ )
printf("*(p + %d) = %lf, p[i] = %lf\n", i, *(p+i), p[i] );
free(p); // Un-reserve the second array
}
|
Output:
*(p + 0) = 0.000000, p[i] = 0.000000 (SAME value !!!) *(p + 1) = 1.000000, p[i] = 1.000000 *(p + 2) = 2.000000, p[i] = 2.000000 *(p + 3) = 3.000000, p[i] = 3.000000 *(p + 4) = 4.000000, p[i] = 4.000000 *(p + 5) = 5.000000, p[i] = 5.000000 *(p + 6) = 6.000000, p[i] = 6.000000 *(p + 7) = 7.000000, p[i] = 7.000000 *(p + 8) = 8.000000, p[i] = 8.000000 *(p + 9) = 9.000000, p[i] = 9.000000 *(p + 0) = 0.000000, p[i] = 0.000000 *(p + 1) = 1.000000, p[i] = 1.000000 *(p + 2) = 4.000000, p[i] = 4.000000 *(p + 3) = 9.000000, p[i] = 9.000000 |
How to run the program:
|
void print( int N, double x[ ] )
{
int i;
for ( i = 0; i < N; i++ )
printf("%lf\n", x[i] );
}
int main( int argc, char *argv[ ] )
{
double a[10];
print( a ) ;
}
|
|
void print( int N, double *x )
{
int i;
for ( i = 0; i < N; i++ )
printf("%lf\n", x[i] ); // x[i] <==> *(x + i) !!!
}
int main( int argc, char *argv[ ] )
{
double a[10];
print( a ) ;
}
|
|
|
#define NRows 3
#define NCols 4
int main(int argc, char *argv[])
{
int i, j;
double* p; // We uses this reference variable to access
// dynamically created array elements
p = calloc(NRows*NCols, sizeof(double) ); // 3x4 = 12 elements
for ( i = 0; i < NRows; i++ )
for ( j = 0; j < NCols; j++ )
p[i*NCols+j] = i+j; // put value i+j in array element p[i][j]
for ( i = 0; i < NRows; i++ )
{
for ( j = 0; j < NCols; j++ )
printf("p[%d][%d] = %lf ", i, j, p[i*NCols+j] );
putchar('\n');
}
free(p); // Un-reserve the first array
}
|
Result:
p[0][0] = 0.000000 p[0][1] = 1.000000 p[0][2] = 2.000000 p[0][3] = 3.000000 p[1][0] = 1.000000 p[1][1] = 2.000000 p[1][2] = 3.000000 p[1][3] = 4.000000 p[2][0] = 2.000000 p[2][1] = 3.000000 p[2][2] = 4.000000 p[2][3] = 5.000000 |
How to run the program:
|