Create random matrix with size passed as arguments











up vote
0
down vote

favorite












I have a very simple question. The following code (with the purpose of creating a random matrix of ints) does not compile. Specifically the line



int m[nrow * ncol];


in the randomMatrix function causes the problem. It says the expression nrow*ncol has to be a constant value. I am new to C++ hence my attempts have been uncreative (e.g. putting 'const' in front of the arguments).



Can someone give me a hint?
Thank you.



#include "pch.h"
#include <iostream>
#include <ctime>

using namespace std;

int* randomMatrix(int nrow, int ncol) {
int m[nrow * ncol];
int index;
for (int col = 0; col < ncol; col++) {
for (int row = 0; row < nrow; row++) {
index = nrow * col + row;
m[index] = rand() % 2;
}
}
return m;
}


int main() {
const unsigned int nrow = 10;
const unsigned int ncol = 10;

int m[nrow * ncol];
m = randomMatrix(nrow, ncol);
print(m, nrow, ncol);
system("PAUSE");
}









share|improve this question






















  • Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
    – Nelfeal
    Nov 8 at 10:32












  • I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
    – Mika Prouk
    Nov 8 at 10:45















up vote
0
down vote

favorite












I have a very simple question. The following code (with the purpose of creating a random matrix of ints) does not compile. Specifically the line



int m[nrow * ncol];


in the randomMatrix function causes the problem. It says the expression nrow*ncol has to be a constant value. I am new to C++ hence my attempts have been uncreative (e.g. putting 'const' in front of the arguments).



Can someone give me a hint?
Thank you.



#include "pch.h"
#include <iostream>
#include <ctime>

using namespace std;

int* randomMatrix(int nrow, int ncol) {
int m[nrow * ncol];
int index;
for (int col = 0; col < ncol; col++) {
for (int row = 0; row < nrow; row++) {
index = nrow * col + row;
m[index] = rand() % 2;
}
}
return m;
}


int main() {
const unsigned int nrow = 10;
const unsigned int ncol = 10;

int m[nrow * ncol];
m = randomMatrix(nrow, ncol);
print(m, nrow, ncol);
system("PAUSE");
}









share|improve this question






















  • Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
    – Nelfeal
    Nov 8 at 10:32












  • I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
    – Mika Prouk
    Nov 8 at 10:45













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a very simple question. The following code (with the purpose of creating a random matrix of ints) does not compile. Specifically the line



int m[nrow * ncol];


in the randomMatrix function causes the problem. It says the expression nrow*ncol has to be a constant value. I am new to C++ hence my attempts have been uncreative (e.g. putting 'const' in front of the arguments).



Can someone give me a hint?
Thank you.



#include "pch.h"
#include <iostream>
#include <ctime>

using namespace std;

int* randomMatrix(int nrow, int ncol) {
int m[nrow * ncol];
int index;
for (int col = 0; col < ncol; col++) {
for (int row = 0; row < nrow; row++) {
index = nrow * col + row;
m[index] = rand() % 2;
}
}
return m;
}


int main() {
const unsigned int nrow = 10;
const unsigned int ncol = 10;

int m[nrow * ncol];
m = randomMatrix(nrow, ncol);
print(m, nrow, ncol);
system("PAUSE");
}









share|improve this question













I have a very simple question. The following code (with the purpose of creating a random matrix of ints) does not compile. Specifically the line



int m[nrow * ncol];


in the randomMatrix function causes the problem. It says the expression nrow*ncol has to be a constant value. I am new to C++ hence my attempts have been uncreative (e.g. putting 'const' in front of the arguments).



Can someone give me a hint?
Thank you.



#include "pch.h"
#include <iostream>
#include <ctime>

using namespace std;

int* randomMatrix(int nrow, int ncol) {
int m[nrow * ncol];
int index;
for (int col = 0; col < ncol; col++) {
for (int row = 0; row < nrow; row++) {
index = nrow * col + row;
m[index] = rand() % 2;
}
}
return m;
}


int main() {
const unsigned int nrow = 10;
const unsigned int ncol = 10;

int m[nrow * ncol];
m = randomMatrix(nrow, ncol);
print(m, nrow, ncol);
system("PAUSE");
}






c++ arrays






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 8 at 10:28









Mika Prouk

248213




248213












  • Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
    – Nelfeal
    Nov 8 at 10:32












  • I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
    – Mika Prouk
    Nov 8 at 10:45


















  • Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
    – Nelfeal
    Nov 8 at 10:32












  • I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
    – Mika Prouk
    Nov 8 at 10:45
















Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
– Nelfeal
Nov 8 at 10:32






Use a std::array, a std::vector, or put constexpr instead of const. Don't return a temporary from a function (m in randomMatrix). Better yet, use iterators. Even better, use a standard algorithm with a lambda (for_each in this case). But I guess you don't know about all of that yet.
– Nelfeal
Nov 8 at 10:32














I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
– Mika Prouk
Nov 8 at 10:45




I used vector. And you are right. I don't know nothing from what you mentioned. But I promise the next silly question will follow. But: Thanks.
– Mika Prouk
Nov 8 at 10:45












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










You are getting an error because arrays lengths must be known at compile time. You are writing code that creates an array, but the length is only known at runtime... This means the compiler doesn't know how much space to allocate and you have to do it yourself. You could use malloc when you create the array - but I wouldn't recommend it.



The best bet is to use std::vector instead of an array.






share|improve this answer






























    up vote
    0
    down vote













    The size of an array in C++ must be fixed at compile time. You can not have it depend on non-const parameters.



    You should not use C-style arrays in C++ unless there is a good reason for it. The idiomatic way if the length is unknown at compile-time is to use a std::vector:



    #include<vector> // <- At top

    std::vector<int> m(nrow*ncol); // Instead of int m[nrow*ncol]


    The return type of your function should then just be std::vector<int>.






    share|improve this answer








    New contributor




    eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.


















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205843%2fcreate-random-matrix-with-size-passed-as-arguments%23new-answer', 'question_page');
      }
      );

      Post as a guest
































      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote



      accepted










      You are getting an error because arrays lengths must be known at compile time. You are writing code that creates an array, but the length is only known at runtime... This means the compiler doesn't know how much space to allocate and you have to do it yourself. You could use malloc when you create the array - but I wouldn't recommend it.



      The best bet is to use std::vector instead of an array.






      share|improve this answer



























        up vote
        0
        down vote



        accepted










        You are getting an error because arrays lengths must be known at compile time. You are writing code that creates an array, but the length is only known at runtime... This means the compiler doesn't know how much space to allocate and you have to do it yourself. You could use malloc when you create the array - but I wouldn't recommend it.



        The best bet is to use std::vector instead of an array.






        share|improve this answer

























          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          You are getting an error because arrays lengths must be known at compile time. You are writing code that creates an array, but the length is only known at runtime... This means the compiler doesn't know how much space to allocate and you have to do it yourself. You could use malloc when you create the array - but I wouldn't recommend it.



          The best bet is to use std::vector instead of an array.






          share|improve this answer














          You are getting an error because arrays lengths must be known at compile time. You are writing code that creates an array, but the length is only known at runtime... This means the compiler doesn't know how much space to allocate and you have to do it yourself. You could use malloc when you create the array - but I wouldn't recommend it.



          The best bet is to use std::vector instead of an array.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 8 at 11:57

























          answered Nov 8 at 10:37









          Theo Emms

          1475




          1475
























              up vote
              0
              down vote













              The size of an array in C++ must be fixed at compile time. You can not have it depend on non-const parameters.



              You should not use C-style arrays in C++ unless there is a good reason for it. The idiomatic way if the length is unknown at compile-time is to use a std::vector:



              #include<vector> // <- At top

              std::vector<int> m(nrow*ncol); // Instead of int m[nrow*ncol]


              The return type of your function should then just be std::vector<int>.






              share|improve this answer








              New contributor




              eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






















                up vote
                0
                down vote













                The size of an array in C++ must be fixed at compile time. You can not have it depend on non-const parameters.



                You should not use C-style arrays in C++ unless there is a good reason for it. The idiomatic way if the length is unknown at compile-time is to use a std::vector:



                #include<vector> // <- At top

                std::vector<int> m(nrow*ncol); // Instead of int m[nrow*ncol]


                The return type of your function should then just be std::vector<int>.






                share|improve this answer








                New contributor




                eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.




















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  The size of an array in C++ must be fixed at compile time. You can not have it depend on non-const parameters.



                  You should not use C-style arrays in C++ unless there is a good reason for it. The idiomatic way if the length is unknown at compile-time is to use a std::vector:



                  #include<vector> // <- At top

                  std::vector<int> m(nrow*ncol); // Instead of int m[nrow*ncol]


                  The return type of your function should then just be std::vector<int>.






                  share|improve this answer








                  New contributor




                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  The size of an array in C++ must be fixed at compile time. You can not have it depend on non-const parameters.



                  You should not use C-style arrays in C++ unless there is a good reason for it. The idiomatic way if the length is unknown at compile-time is to use a std::vector:



                  #include<vector> // <- At top

                  std::vector<int> m(nrow*ncol); // Instead of int m[nrow*ncol]


                  The return type of your function should then just be std::vector<int>.







                  share|improve this answer








                  New contributor




                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  share|improve this answer



                  share|improve this answer






                  New contributor




                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered Nov 8 at 10:37









                  eukaryota

                  3919




                  3919




                  New contributor




                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  eukaryota is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205843%2fcreate-random-matrix-with-size-passed-as-arguments%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest




















































































                      Popular posts from this blog

                      How to pass form data using jquery Ajax to insert data in database?

                      National Museum of Racing and Hall of Fame

                      Guess what letter conforming each word