array

Feb 27, 2016 at 3:55pm
Hi everybody.I can't initialize two-dimensional array. Eror in function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include<iomanip>
using namespace std;
void init(int pmtx[][],int r,int c)
{
	for(int i=0;i<r;i++)
	{
		for(int j=0;j<c;j++)
		{
			pmtx[i][j]=rand()%75;
		}
	}
}
int main()
{
   int r=0;
   int c=0;
   cout<<"enter r "<<endl;
   cin>>r;
   cout<<"enter c "<<endl;
   cin>>c;
   init(pmtx,r,c);

	return 0;
}
Last edited on Feb 27, 2016 at 8:52pm
Feb 27, 2016 at 4:33pm
closed account (2UD8vCM9)
First off you may want to check out this link http://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function


Questions regarding your question:
Is this for school?

I'm asking so I can know what tools you are allowed to use for this.

Do you know what the max value of r and c will ever be?

Have you learned pointers?



Feb 27, 2016 at 8:16pm
yes, it is for school.
right now i'm studing pointers.
No i don't know max value for r and c, let it be 5 and 5 (matrix)
Feb 27, 2016 at 10:01pm
I am afraid toy need to create your array dynamically, after you know the number of rows and columns. Here is a way to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

void init (int *array, int row_count, int col_count);
void print_array (int *array, int row_count, int col_count);

int main ()
{
  int row = 0, col = 0;
  srand ((unsigned)time(0));
  cout << "enter row: "; 
  cin >> row;
  cout << "enter col: ";
  cin >> col;

  int *array = new int[row * col];

  init (array, row, col);
  print_array (array, row, col);
  
  delete [] array;
  system ("pause");
  return 0;
}

void init (int *array, int row_count, int col_count)
{
  for (int row = 0; row < row_count; row++)
  {
    for (int col = 0; col < col_count; col++)
    {
      array[row * col_count + col] = rand () % 75;
      // http://stackoverflow.com/questions/1817631/iterating-one-dimension-array-as-two-dimension-array
    }
  }
}

void print_array (int *array, int row_count, int col_count)
{
  for (int row = 0; row < row_count; row++)
  {
    for (int col = 0; col < col_count; col++)
    {
      cout << array[row * col_count + col] << ' ';
    }
    cout << '\n';
  }
}
Feb 28, 2016 at 2:07pm
Thomas, very thanks. Just right. I just can't understand why SRAND ??? Can you explain to me? Please.
Last edited on Feb 28, 2016 at 2:40pm
Feb 28, 2016 at 3:38pm
srand is neccessary to initialize the random generator otherwise you always get the same numbers.
http://www.cplusplus.com/reference/cstdlib/srand/
Topic archived. No new replies allowed.