Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ how to initialize const elements of an array

i need a way to initialize const elements of an array for the program i am currently working on. The problem is that i have to initialize these elements with a function, there is no way to do it like this:

const int array[255] = {1, 1278632, 188, ...};

because its alot of data i have to generate. What i tried is to memcpy data to the const int's but that can't work and hasn't worked.

 const int array[255];

 void generateData(){
      for(int i = 0; i < 255; i++) {
          initializeSomehowTo(5, array[i]);
      }
 }

I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it.

like image 805
Darius Duesentrieb Avatar asked Jun 05 '17 22:06

Darius Duesentrieb


People also ask

How do you initialize a const member?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Can arrays be const?

Arrays are Not Constants The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

How do you assign an array to constant?

In C#, use readonly to declare a const array. public static readonly string[] a = { "Car", "Motorbike", "Cab" }; In readonly, you can set the value at runtime as well unlike const.


1 Answers

How about this?

#include <array>
typedef std::array<int, 255> Array;

const Array array = generateData();

Array generateData(){
    Array a;
    for(int i = 0; i < a.size(); i++) {
        initializeSomehowTo(a[i]);
    }
    return a;
}
like image 55
Arun Avatar answered Sep 19 '22 14:09

Arun