Code:
/*
* code.c
*/
#include <stdio.h>
void printArray(int iXArray, int iSize);
int main() {
int array1[] = {7, 9, 3, 18};
int *array2[] = {array1 + 0, array1 + 1, array1 + 2, array1 + 3};
printArray(array2, 4);
return 0;
}
// This should print the values in array1
void printArray(int iXArray, int iSize) {
int iCntr;
for (iCntr = 0; iCntr < iSize; iCntr++) {
printf("%d ", *iXArray[iCntr]);
}
printf("\n");
}
My compiler doesn’t approve of this code.
– [Warning] passing arg 1 of `printArray’ makes integer from pointer without a cast
– printArray(array2, 4);
– [Error] subscripted value is neither array nor pointer
– printf(“%d “, *iXArray[iCntr]);
What am I doing wrong, and why? How do I fix this?
Try this:
In your example you provide an array of (int*) so reference it as one, you must tell the compiler to expect an array of pointers.
By default passing an array is by reference. If you change the array’s content, it changes at the callee’s side aswell. The pointer itself is passed by value, so changing the value of the iXArray parameter (
iXArray = (int**)123;) will not change thearray2pointer at the callee’s side.If you want to pass the array by value, will need to wrap it in a value type: