Link
Link

Reputation: 23

Passing simple pointer as double pointer to function

I have to write a program that multiplies two vectors for my coding class and the argument types of the implemented functions are set by our teacher.

I can not figure out how to pass the vectors, which are one dimensional arrays, as double pointers to one of the implemented functions.

I have tried to use the address-operator, since I want to point to the address of the beginning of the array, where the function is supposed to reserve memory space for the array. But the compiler always tells me

incompatible pointer type, expected int **

and it does not work without any operator either.

//all functions set by worksheet
int array_create(int **v, int n);//function with double pointer argument
void array_init(int *v, int n);
int mult_array(int *x, int *y, int n);

int main(void)
{
    int i, j;
    int x[10];
    int y[10];
    srand(time(NULL));
    array_create(x, 7); // see here
    array_create(y, 7); // see here
    array_init(x, 7);
    array_init(y, 7);
    printf("\nResult: %i", mult_array(x, y, 7));
    array_destroy(x);
    array_destroy(y);
    return 0;
}

int array_create(int **v, int n)
{

    v = malloc(n * sizeof(int));
    if(!v){
        return 0;
    }
    return 1;
}

Upvotes: 2

Views: 41

Answers (1)

bruno
bruno

Reputation: 32586

visibly the goal of array_create is to allocate and save the address in the first parameter, so change it to be :

int array_create(int **v, int n)   
{
  *v = malloc(n * sizeof(int));
  if(!*v){
      return 0;
  }
  return 1;
}

you need to call is in the right way :

int * x;
int * y;
srand(time(NULL));
array_create(&x, 7);
array_create(&y, 7);

x and y now contains the addresses of the allocated memory blocks (supposing there are enough memory). while array_create return 0 or 1 it can be a good idea to test the returned value ;-).

Upvotes: 2

Related Questions