在C中为数组元素分配随机值

时间:2017-02-01 17:42:08

标签: c arrays

我编写了一个程序,要求用户输入两个数字M和N.将会有一个数组,其中包含需要为其分配随机值的M * N个元素。然后,这些值显示在M×N表中。问题是,当我运行程序时,第一个元素的赋值总是0或者某个奇怪的数字,如-2147197728,其余的元素总是0.可以有人帮帮我吗?

#include <stdio.h>
#include <stdlib.h>

int PopulateRandom(int M, int N);
int PrintArray2D(int M, int N);

// Prints elements of array in a M x N table
int PrintArray2D(int M, int N){
int array[M*N], row, column, i = 0;

while(row <= M && column <= N){
    for(row = 1; row <= M; row++){
        for(column = 1; column <= N; column++){
            array[i] = PopulateRandom(M, N);
            printf("%d  ", array[i]);
            if(column == 4){
                break;
            }
        }
        column = 0;
        printf("\n");
    }
}
return array[i];
}

//Assigns elements of the array "array" random values
int PopulateRandom(int M, int N){
int i, array[M * N];

for(i = 0; i < M*N; i++){
    array[i] = rand() % (M*N) - 1;
}
return array[i];
}

int main(void){
int option, M, N;

printf("If you would like to search ann array, enter 1 \n: ");
printf("If you would like to exit, enter 0 \n: ");
scanf("%d", &option);

while(option != 0){
    switch(option){
        case 1: if(option == 1){
                printf("Enter two numbers M and N: ");                          
                scanf("%d %d", &M, &N);
                PrintArray2D(M, N);
        }
        case 0: if(option == 0){
            break;
        }
    }
    printf("If you would like to search ann array, enter 1 \n: ");
    printf("If you would like to exit, enter 0 \n: ");
    scanf("%d", &option);
}
}

1 个答案:

答案 0 :(得分:0)

您将在此处返回数组之外的索引处的值

   int PopulateRandom(int M, int N){
       int i, array[M * N];

       for(i = 0; i < M*N; i++){
           array[i] = rand() % (M*N) - 1;
       }
       return array[i];
   }

当循环结束时,我将等于M * N,因为数组的大小是M * N,所以array [i]将在数组之外。