PianoEntropy
PianoEntropy

Reputation: 131

Array of pointers as function argument

How do I feed an array of pointers as an argument to a function?

In the code below, if I want my function f to take an array of pointers int *x[], how should I declare x in main() and feed it as argument to f?

void f(int *x[]){ 
     int data[5] = {1,2,3,4,5};
     int k;
     for(k=0; k<5; k++){ 
        x[k] = &(data[k]);
     }
}

int main(){
    int *(x[]), k, l=5;
    f(x); // this does not work
    for(k=0; k<l; k++){ 
        printf("x[%d] = %d\n", k, *x[k]);
        }
    }
    return 0;
}

Writing f(x) does not work, and neither does f(x[]) or f(x[5]).

In fact, the declaration int *(x[]) is already not recognized by my compiler, while I thought that one could declare an array of pointers without specifying the length of the array.

Upvotes: 0

Views: 138

Answers (3)

fushi
fushi

Reputation: 1

An alternate way to declare an array of pointer as a parameter is to use a pointer of pointer

void f(int **x, int size){ 
  //code
}

However, you'll have to pass the size as a second argument if you want to avoid an overflow.

To call the code you'll just have to do something like this :

int *a[] = { NULL, NULL, NULL};
f(a, 3);

Upvotes: 0

haccks
haccks

Reputation: 106012

In main, change

int *(x[])  

to

int *x[SIZE]; // SIZE is array size    

Note that, you can't declare a zero size array in C except when it is a last member of a structure.

After all, your code will invoke undefined behavior because the variable data is an automatic local variable and will not exist after function returns.

You may want this:

void f(int *x[]){ 
     int *data = malloc(5*sizeof(int);
     int temp[5] = {1,2,3,4,5};
     memcpy(data, temp, 5*sizeof(int));
     int k;
     for(k=0; k<5; k++){ 
         x[k] = &(data[k]);
     }
} 

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

First of all your code has no sense because you are trying to fill an array of pointers that will point to local variables. That is after exiti8ng the function all pointers will be invalid because original objects will be already destroyed. The code could have a sense if the array in the function would have static storage duration

void f(int *x[]){ 
     static int data[5] = {1,2,3,4,5};
     int k;
     for(k=0; k<5; k++){ 
        x[k] = &(data[k]);
     }
}

In main array x should be defined at least as

int * x[5];


int main(){
    int * x[5], k;

    f(x); 

    for ( k=0; k < 5; k++ ){ 
        printf("x[%d] = %d\n", k, *x[k]);
        }
    }
    return 0;
}

Upvotes: 1

Related Questions