Well the first problem is learning how to format code - random indentation and arbitrary placement of braces does not make for easy to follow code.
Eg, this is yours reformatted
Code:
void rand_gen(int need_num, int **array, int dim)
{
int n, m, *temp_array;
int i = 0, b, g, new1;
int q, w, h;
temp_array = (int *) malloc((need_num + 1) * sizeof(int));
for (h = 0; h < (need_num + 1); h++) {
temp_array[h] = 0;
}
srand(time(NULL));
for (i = 0; i < (need_num); i++) {
b = rand() % (need_num) + 1; // random number within need_num
//temp storing the rand # in a array temp
new1 = 1;
for (g = 0; g < i; g++)
if (temp_array[g] == b) {
new1 = 0;
}
if (new1 == 1) {
temp_array[i] = b;
} else
i--;
}
//initialize array to 0
for (q = 0; q < dim; q++) {
for (w = 0; w < dim; w++) {
array[q][w] = 0;
}
}
//filling actual array,
for (n = 0; n < dim; n++) {
for (m = 0; m < dim; m++) {
if (i < need_num) {
array[n][m] = temp_array[i];
i++;
}
}
}
}
> temp_array = (int *) malloc((need_num + 1) * sizeof(int));
1. you cast the result of malloc - see the FAQ for why this is bad
2. you don't free it at the end - this is a memory leak
3. you don't need it anyway.
> srand(time(NULL));
Typically, you do this ONCE at the beginning of main.
If you called this code within the same second, you're going to end up with exactly the same results.
Try this approach
Code:
void rand_gen(int need_num, int **array, int dim)
{
int i, r, c;
/* fill with zeros */
for ( r = 0 ; r < dim ; r++ ) {
for ( c = 0 ; c < dim ; c++ ) {
array[r][c] = 0;
}
}
/* put 1..need_num in random places */
for ( i = 1 ; i <= need_num ; i++ ) {
r = rand() % dim; /* pick a spot */
c = rand() % dim;
if ( array[r][c] == 0 ) {
array[r][c] = i; /* it's empty, fill it */
}
}
}
A better way would be to just put 1..need_num in the first positions of the matrix (and fill the rest with zeros), then implement a shuffle.
A nice easy exercise for you.