Isabel Longo
Isabel Longo

Reputation: 11

When passing a 2d array as parameter with pointers to print its values it only prints zero

So, i have to make a function that takes a 2d array as parameter with a pointer, specifically, so that cant be changed.

This function that i wrote works, but when i print it, it only prints zeros. When printing directly in main() it works normally.

Thanks in advance!

Code:

void calcula_media(float (*matriz)[3]){

    int i, j;
    
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            *(*(matriz+i)+j)=i+j;
            printf("%.1f ", (*(matriz+i)+j));
        }
    }
    
}

void main(){

    float matriz[3][3]={1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i, j;
    
    calcula_media(matriz[3]);

    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            printf("%.1f ", *(*(matriz+i)+j));
        }
    }
}

Upvotes: 0

Views: 46

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

The argument expression in this call

calcula_media(matriz[3]);

is incorrect. It has the type float * (and moreover the pointer expression points outside the array matriz) while the function expects an argument of the type float (*matriz)[3]

void calcula_media(float (*matriz)[3]){

Call the function like

calcula_media(matriz);

In this case the array designator is implicitly converted to pointer to its first element that has the type float[3].

And in this call of printf

printf("%.1f ", (*(matriz+i)+j));

you need to dereference the pointer expression

printf("%.1f ", *(*(matriz+i)+j));

Upvotes: 1

Related Questions