2017-02-01 46 views
1

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

#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); 
} 
} 
+2

'row'和'column'是*未初始化的变量*。请注意,C中的数组通常从'0'索引。在这些情况下(很少),当从'1'索引数组很方便时,数组必须大1个元素,因此上限不会被破坏。 –

+0

您的'PopulateRandom'函数将返回数组的值*超出范围*。它并不真正使用的数组。函数可以包含唯一的语句'return rand()%(M * N) - 1;' –

+0

我在for循环中初始化'row'和'column'。 –

回答

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。