我编写了一个程序,要求用户输入两个数字 M 和 N。将有一个包含 M*N 个元素的数组需要分配随机值。这些值然后显示在 M x 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);
}
}
最佳答案
你要返回一个保存在你的数组之外的索引处的值
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];
}
当循环结束时,i 将等于 M * N,array[i] 将在 array 之外,因为 array 的大小为 M*N。
关于c - 在 C 中为数组的元素分配随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41986202/