Passing an array containing pointers to a function properly
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)
This works also:
/*
* 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");
}
Pointer arithmetics works perfectly.
Regarding the "stay untouched". You are passing things by reference so the way to keep them from being edited is to make them const. You have a couple different options based on what part you don't want to change. However, that won't let you change them in you function. What it sounds like is you want a pass-by-value which you can't get in C++ using arrays unless you make your own manual copy.
This seems to work without making array1 editable by printArray.
/*
* 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");
}
精彩评论