Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
        }
    }
}

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading