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

标签 c arrays

我编写了一个程序,要求用户输入两个数字 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/

相关文章:

c - 在 C 中的 block 范围内的变量声明之后使用 goto

java - 缓冲区溢出 (vs) 缓冲区溢出 (vs) 堆栈溢出

c# - 从 byte[] 创建 AudioClip

javascript - 循环遍历对象的嵌套数组

从数组中按级别顺序创建二叉树

c - 从列表中搜索缓冲区以查找任何字符串的高效算法

arrays - 如何使用 Mongoose 从数组中删除对象

arrays - 在 Rust 中,当其他字符不感知时,将字符串拆分为 Vec<String> 字符的最佳方法?

python - 数组怎么能是指数呢?

c - 从函数 C 分配数组和赋值