简体   繁体   中英

Passing an array to a function changes its values?

The intended result is the printing of the same values that we input, but the output is zero after the first row.

#include<stdio.h>
void display(int *q, int);

int main() {
    int i,j,n;
    int d[50][50];
    printf("Input the order\t");
    scanf("%d", &n);

    for (i=0;i<=(n-1);i++) {
        for (j=0;j<=(n-1);j++) {
            scanf("%d", &d[i][j]);
        }
    }
    display (d, n);
}

void display (int *q, int r) {
    int i,j;

    for (i=0;i<r;i++) {
        for (j=0;j<r;j++) {
            printf("%d\t", *(q + i*r + j));
        }
        printf("\n");
    }
}

your display routine assumes that the 2D array is [n][n] whereas it is [50][50] .

You have to pass the actual 2D array dimension alongside with n , the display routine cannot know the actual 2D array size.

You could declare your array dynamically like this:

   printf("Input the order\t");
   scanf("%d", &n);
   int d[n][n];

and then avoid the warning

test.c:20:18: warning: passing argument 1 of 'display' from incompatible pointer type
         display (d, n);

here by casting explicitly to 1D pointer (since you know the structure):

display ((int*)d, n);

Your function is declared with a parameter of type int * . You are attempting to pass an argument of type int [50][50] , which decays to pointer type int (*)[50] . These pointer types are incompatible. Language does not support implicit conversion from int (*)[50] to int . Your code is not a valid C program, and I'm sure your compiler told you about it.

A more meaningful thing to do would be to declare your function as

void display (int n, int q[n][n])

and access your array elements in a natural way as

q[i][j]

However, for that you will have to use true array sizes as n (ie 50 in your case). If you want to process a smaller sub-matrix of elements, you will have to pass its size separately.

But if you really want to use your "hack", you will have to use an explicit cast when calling your function

display ((int *) d, n);

and keep in mind that each row of your original array still contains 50 elements, as declared, regardless of the value of n . This means that inside your function you will have to use 50 as row size multiplier

void display (int *q, int r) {
    int i,j;

    for (i=0;i<r;i++) {
        for (j=0;j<r;j++) {
            printf("%d\t", *(q + i*50 + j));
        }
        printf("\n");
    }
}

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