Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array of random #'s 1

Status
Not open for further replies.

tan6262

Programmer
Nov 1, 2000
3
US
need a function outside of main to fill a 2-D array with random numbers in the range
of 0 to 99, for example: rand () % 100. the prototype declaration is:
void fill (int *rows, int *cols, int ***array); where all three were declared in main and the values for rows and cols were read in by the user in another function.
 
Im assuming that *rows is a pointer to an integer that contains the number of rows in the array, *cols is a pointer to an integer that contains the number of columns in the array, and that ***array is a pointer to the array which has already been declared and allocated the necessary memory that it needs.

That being the case, it is pretty simple and straightforward:


void fill( int *rows, int *cols, int ***array )
{
int a, b;
for ( a = 0; a < *rows; a++)
{
for ( b = 0; b < *cols; b++)
{
*array[a] = rand() % 100;
}
}
}


If Im assuming too much, let me know... ;)


Regards,
Gerald
 
Why do you need int ***array. You can do with **array for 2-D array. Also , if you have already passed the array which has been allocated sufficient memory . Then the function of gerald will do . But if you need to allocate memory inside the function itself . Then just modify the function as:

void fill( int *rows, int *cols, int **array )
{
array = (int**) malloc(sizeof(int*) * (*rows));
for(int i = 0;i < rows ;i++)
array = (int*) malloc(sizeof(int)* (*cols));

int a, b;

for ( a = 0; a < *rows; a++)
{
for ( b = 0; b < *cols; b++)
{
array[a] = rand() % 100;
}
}
}




Siddhartha Singh
siddhu_singh@hotmail.com
siddhu.freehosting.net
 
Unfortunately, that is not very random. Each invocation will produce the same set of random numbers as rand() will use a seed value of 1 every time. Call srand() before the loop.

ex.

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

...

srand((unsigned)time(NULL));

for ( b = 0; b < *cols; b++)
{
*array[a] = rand() % 100;
}


Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top