【问题标题】:The problem of creating a dynamic array and fill random numbers创建动态数组并填充随机数的问题
【发布时间】:2020-09-12 08:02:57
【问题描述】:

*当我想将随机数填充到数组时出现错误。 我认为问题在于指针 错误在这里 ' ptr[i][j]= rand() % 40000 +5; '* 错误名称:下标值既不是数组也不是指针也不是向量

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

int* create_matrix_fill_random (int satir,int sutun);


int main()
{
    srand(time(NULL));
    printf("Matrix automatically created 3x3");
    int a=3;
    int *matrix = create_matrix_fill_random(a,a);

    return 0;
}

int* create_matrix_fill_random (int row, int col)
{
    int *ptr;
    ptr = malloc(row*col*sizeof(int));
    int i,j;
    for (i=0;i<row;i++){
        for (j=0;j<col;j++){
        ptr[i][j]= rand() % 40000 +5;
    //Mistake ^ ^ ^ ^ ^ ^ 
        }
    }
    return ptr;
}

【问题讨论】:

  • @ArdentCoder 或者甚至是ptr[i + j * col]
  • @AdrianMole 当然,我只是在暗示将二维数组投影到一维数组上。 OP 可以以行主要形式或列主要形式:)
  • @ArdentCoder 但是你的“公式”是错误的!另一个选项是ptr[i * col + j]
  • @AdrianMole Lol 我没注意,使用库来完成这些任务让我忘记了基础知识:P

标签: c arrays pointers function-pointers void


【解决方案1】:

函数中的变量ptr 的类型为int *。因此,像 ptr[i] 这样应用下标运算符一次,您将获得一个类型为 int 的标量对象,您可能不会再对其应用下标运算符。

如果您的编译器支持可变长度数组,那么您可以编写

int ( *matrix )[a] = create_matrix_fill_random(a,a);

函数看起来像

int ( * create_matrix_fill_random (int row, int col) )[]
{
    int ( *ptr )[col];
    ptr = malloc( sizeof( int[row][col] ) );
    int i,j;
    for (i=0;i<row;i++){
        for (j=0;j<col;j++){
        ptr[i][j]= rand() % 40000 +5;
        }
    }
    return ptr;
}

否则你必须写

int **matrix = create_matrix_fill_random(a,a);

函数看起来像

int ** create_matrix_fill_random (int row, int col)
{
    int **ptr;
    ptr = malloc( sizeof( row * sizeof( int * ) );

    int i,j;

    for ( i = 0; i < row; i++ )
    {
        ptr[i] = malloc( col * sizeof( int ) );
    }

    for (i=0;i<row;i++){
        for (j=0;j<col;j++){
        ptr[i][j]= rand() % 40000 +5;
        }
    }
    return ptr;
}

【讨论】:

  • @ArdentCoder 也许有错字。我更新了帖子。
  • 好吧,又一个(愚蠢的错误):您是否忘记删除那些指示原始错误的代码cmets?
  • @Vlad "如果您的编译器支持可变长度数组" - 可以添加测试场景并检查宏 __STDC_NO_VLA__ 的值。
  • @ArdentCoder 谢谢。我删除了评论。
  • 减号是一个奇怪的释放过程,尤其是当其中一个分配失败时。不喜欢这种方式。最好使用索引算法来模拟多暗度测定。
【解决方案2】:

你有一个一维数组,所以你只能使用一个索引。

ptr[i * cols + j]= rand() % 40000 +5;
// ^^^^^^^^^^^^^^

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 2017-06-04
    • 2011-01-23
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多