In the below code, I made an integer array and tried printing it with the function DisplayIntArray in order to try to understand how pointers work.
Some questions are embedded in the comments.
/*==========================================================
* pointer tests
*========================================================*/
#include <stdio.h>
void DisplayIntArray(char *Name, int *Data, int lenArray) {
/* Display integer array data */
int m;
printf("%s = \n", Name);
for(m = 0; m < lenArray; m++, printf("\n")){
printf("%d ", *(Data+m));
printf("%d ", Data[m]);
// how come these two print statements display the same thing?
}
}
void DisplayDoubleArray(char *Name, double *Data, int lenArray) {
/* Display double array data */
int m;
printf("%s = \n", Name);
for(m = 0; m < lenArray; m++, printf("\n")){
printf("%f ", *(Data+m));
printf("%f ", Data[m]);
}
}
int main ()
{
int int_array[5] = {1, 2, 3, 4, 5};
int *int_array_p = &int_array[0];
// print array with function DisplayIntArray
// this works fine
DisplayIntArray("int array", int_array_p, 5);
printf("\n");
// Curiously the function still works when passing the actual
// array instead of the pointer.
DisplayIntArray("int array", int_array, 5);
printf("\n");
// print array using the wrong function
// This print should fail because I'm passing an integer value pointer
// into a double. But shouldn't it print the first element
// correctly? - Why not?
DisplayDoubleArray("int array", int_array_p, 5);
printf("\n");
return 0;
}
The output of the code is:
int array =
1 1
2 2
3 3
4 4
5 5
int array =
1 1
2 2
3 3
4 4
5 5
int array =
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
-0.000000 -0.000000
0.000000 0.000000