1
MとNの2つの数字を入力するようにプログラムを作成しました。M * N個の要素にランダム値を割り当てる必要がある配列があります。これらの値は、M×Nテーブルに表示されます。問題は、私がプログラムを実行すると、最初の要素の割り当てられた値は常に0か、-2147197728のような奇妙な数であり、残りの要素は常に0です。誰か助けてくれますか?あなたがここにCの配列の要素にランダムな値を代入
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];
}
をご使用のアレイの外にインデックスで開催された値を返している
#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);
}
}
'row'と' column'は*未初期化変数です*。 Cの配列は、通常、 '0'からインデックスされることに注意してください。そのような場合(まれに)、配列を '1'からインデックスすると便利な場合、配列は1要素を大きくしなければならないので、上限は壊れません。 –
あなたの 'PopulateRandom'関数は、配列の*範囲外の*値を返します。途中で実際には使用しない配列です。関数は唯一の文 'return rand()%(M * N) - 1;)を含むこともできます。 –
forループで 'row'と 'column'を初期化しました。 –