Search code examples
carrayspointersfunction-pointersvoid

The problem of creating a dynamic array and fill random numbers


*I get an error when I want to fill random numbers to Array. I think the trouble is in the pointers The error is here ' ptr[i][j]= rand() % 40000 +5; '* Error Name: subscripted value is neither array nor pointer nor vector

#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;
}

Solution

  • You have a one dimentional array, so you can use only one index.

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