Changing values in a matrix using void function

Hi there,

I have the following void function devised to assign "+1" or "-1" to each element of a matrix at random. While the function does what I want, when I print the values of the matrix all are set to zero:
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
#include <vector>
#include "aRand.h"
#include <iostream>

void initConfig(std::vector<std::vector<int> > premat, int nL, int nN) {

  int * pnRand;
  pnRand = 0;

  for (unsigned int i=0; i<nL;++i) {
   pnRand = pnRand_plus(1,100,nN,time(NULL) + i);
  
     for (unsigned int j=0;j<nN;++j) {  
      premat[i][j] = (*(pnRand + j) > 50 ? -1:1);

      std::cout<<*(pnRand + j) << " " << premat[i][j] << std::endl;
     }

   delete[] pnRand;
  }

}

// test driver
int main() {
  int nN = 5;
  int nL = 5;
  std::vector<std::vector<int> > premat(nL, std::vector<int>(nN));
  initConfig(premat,nL,nN);

  for (unsigned int i=0; i<nL; ++i)
    for (unsigned int j=0; j<nN;++j) std::cout << "premat[" << i << "][" << j << "] = " << premat[i][j] << std::endl;

  return 0;
}

The function pnRand_plus returns a pointer to an array of random numbers from 1 to 100, with seed time(NULL) + i.
The values printed in main are zero, despite the values printed during the function run are fine (-1s and +1s).

Any ideas?

Thanks a million!
Last edited on
You are passing a copy to the function.
Pass by reference instead http://www.cplusplus.com/doc/tutorial/functions2/

*(pnRand + j)¿why the obfuscation?

delete[] pnRand; error prone. Make `pnRand_plus' return a std::vector instead
Bravo!! Thanks ne555 :)
Topic archived. No new replies allowed.