arrayscpointers

How to access a double pointer to array in a function


I am a bit confused with this type of C code:

void double_function(double **arr){
printf("Value at 1: %f \n", arr[1]);
}

int main() {

double arr[3] = {0.11,1.2,2.56};
double_function(&arr);

}

This does not print the value 1.2. I tried *(arr)[1] and (*arr[1]) as well, and I can't seem to access it. I keep getting:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Can someone help clarify this notation on how to access the array?

Please note that the specifications require that the function take a double **arr.


Solution

  • The variable arr is an array of doubles and you clarified that you wanted to pass it in a pointer to pointer. Using temporary (double *) { arr } so we pass in its address with &(double *) { arr }:

    #include <stdio.h>
    
    void double_function(double **arr){
        printf("Value at 1: %f \n", (*arr)[1]);
    }
    
    int main() {
        double arr[3] = {0.11,1.2,2.56};
        double_function(&(double *) {arr});
    }