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:
void printArray(int **iXArray, int iSize) ...
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 the array2
pointer at the callee's side.
If you want to pass the array by value, will need to wrap it in a value type:
typedef struct {
int A[123];
} Array;
Array incrementArray(Array array, int count) {
for (int i=0; i<count; i++) {
array.A[i]++;
}
return array;
}
You are passing an array of pointers to int:
void printArray(int *ixArray[], int iSize)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With