Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array containing pointers to a function properly

Tags:

c

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?

like image 584
Pieter Avatar asked Jan 19 '10 13:01

Pieter


2 Answers

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;
}
like image 138
Yannick Motton Avatar answered Nov 15 '22 07:11

Yannick Motton


You are passing an array of pointers to int:

void printArray(int *ixArray[], int iSize)
like image 35
Richard Pennington Avatar answered Nov 15 '22 07:11

Richard Pennington