简体   繁体   中英

How to use helper functions to fill an array of user input size?

This is supposed to be a simple program, first asking the user the size of the square array (from 1 to 10) then asking the user to input the numbers into the array and finally printing out the array with the inputted numbers.

However, now inputting something such as the size of 2, with values 1, 2, 3, 4

Instead of getting the array

1.00  2.00
3.00  4.00

printed out, it prints out a long wall of 0.00's with the correct values somewhere in there.

From my understanding it's required to give bounds when declaring a helper function with a multidimensional array like so void someFunct(int arr[][MAX]); , which in this case I declared the max size to be 10. But if I'm not mistaken the problem might be coming from me doing something wrong there?

The code I was testing:

#include <stdio.h>

int numInput(char[]);
void fillArray(double[][10],int);
void printArray(double[][10],int);

int main() {
   // GET SQUARE ARRAY SIZE
   int n = numInput("Insert the dimension of the square array(1-10): ");
   // FILL THE SQUARE ARRAY A[n][n]
   double A[n][n];
   fillArray(A, n);
   // PRINT OUT ARRAY A[n][n]
   printArray(A, n);

   return 0;
}

int numInput(char text[]){
    int num;
    do{
        printf("%s", text);
        scanf("%d", &num);
    }while(num < 1 || num > 10);
    printf("\n");
    return num;
}

void fillArray(double arr[][10],int size){
    int i, j;
    for(i = 0; i < size; i++){
        for(j = 0; j < size; j++){
            printf("Insert A[%d][%d]: ", i, j);
            scanf("%lf", &arr[i][j]);
        }
    }
}

void printArray(double arr[][10],int size){
    int i, j;
    for(i = 0; i < size; i++){
        for(j = 0; j < size; j++){
            printf("  %.2lf  ", arr[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

Simply change your functions to use the specified variable size:

void fillArray  (int size, double arr[size][size]);
void printArray (int size, double arr[size][size]);

Note that the size parameter needs to be declared to the left of the array parameter.

Change double A[n][n] to double A[10][10]; .

If n is eg 3, then double A[n][n] ends up being a double A[3][3] which is not compatible with a double arr[][10] .

Variable length arrays are not that useful after all, use them with care.

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