helle there.

I need a help in generate random 2D matrix !!

How to write that plz !

Recommended Answers

All 5 Replies

what exactly do you mean? a matrix with random number of rows and columns? a matrix that contains random numbers? Both?

In order to work with a matrix with random number of rows and columns you need to know how to work with pointers, each dimension requires one star, so in a 2d matrix you would have int** array, after that call malloc() to allocate each dimension of the array. Some of the code below may now compile with older C compilers.

int** matrix = 0;
int i;
const int rows = 5;
const int cols = 10;

matrix = (int **)malloc(rows * sizeof(int *)); // allocate rows

// now allocate the columns
for(i = 0; i < rows; i++)
   matrix[i] = (int *)malloc(rows * sizeof(int));

I've built my program without pointer I think thats why the result was wrong!
I need 2 2D matrix (2x4)and (4x3) which contain random numbers between -100 and 80 .

Can I send to u a private message I have a strong excuse to do that and I will tell you why later on if u accept !

Can I send to u a private message

Please read my signature -- I don't accept private messages.

If you know the size of the matrixes then you don't need pointers. Just call rand() to fill the matrices with random numbers. Here is another thread that may help you.

yah I read it, that's why I asked you for a permission !
ok then, I did the following inside the loop of the first array but it doesn't work !

A[i][j]=rand()%179-1 ;
A[i][j]=malloc(sizeof(int));

you don't need malloc() if you have static array sizes. Post the entire loop(s) that you tried, not just one line out of it(them).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.