简体   繁体   中英

Double Pointer to array in Function, How to Access

I am a bit confused with this type of C code (sorry for the elementary question):

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 1.2 value. I tried *(arr)[1] and (*arr[1]) as well, and I can't seem to access it. Can someone help clarify this notation on how to access the array? Thanks. EDIT: Please note that the specifications require that the function take a double **arr

You variable arr is an array of doubles and clarified that you wanted to pass in in a pointer to pointer. Using temporary (double *) { arr } so we pass in it's 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});
}

The parameter passes to the function doesn't match the parameter's type, and you're using the parameter in the function incorrectly.

The function is defined to accept a double ** parameter. Inside the function, it passes arr[1] , which has type double * , to printf using the %f format specifier which expects a double . Also, you're passing a double (*)[3] to the function, ie a pointer to an array, which doesn't match the parameter type.

If you want to pass an array of double to a function, the parameter type should be double * , since an array in most contexts decays to a pointer to its first element.

So change the function's parameter type to double * :

void double_function(double *arr){

And pass the array to the function directly:

double_function(arr);

add a pointer to the array like this:

#include <stdio.h>

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

int main() {

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

}

Allan Wind already provides a nice a clean (as much as it can be) solution, I would add that the requirement of using a pointer to pointer parameter to take a 1D array argument makes little sense when you can use a simple pointer. Look how much more simple it looks:

#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(arr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM