c - 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; }  // should print values in array1 void printarray(int ixarray, int isize) {     int icntr;     (icntr = 0; icntr < isize; icntr++) {         printf("%d ", *ixarray[icntr]);     }     printf("\n"); } 

my compiler doesn't approve of code. - [warning] passing arg 1 of `printarray' makes integer pointer without cast - printarray(array2, 4); - [error] subscripted value neither array nor pointer - printf("%d ", *ixarray[icntr]);

what doing wrong, , why? how fix this?

try this:

void printarray(int **ixarray, int isize) ... 

in example provide array of (int*) reference one, must tell compiler expect array of pointers.

by default passing array reference. if change array's content, changes @ callee's side aswell. pointer passed value, changing value of ixarray parameter (ixarray = (int**)123;) not change array2 pointer @ callee's side.

if want pass array value, need wrap in value type:

typedef struct {   int a[123]; } array;  array incrementarray(array array, int count) {     (int i=0; i<count; i++) {         array.a[i]++;     }     return array; } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -