473,586 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

declaring constant array without initializing all the elements

Hi,
I need to create a consant array of larze size but however its
elements can be calculated using an equation, say for example I need
an int arry of 20 elements where each element will be

arr[i] = 2 + (i*i)

But I want arry to be constant. How can I declare such a constant
array without actually defining all the elements?

I could think of one way:
Declare a non const arry

int arr_non_const[20];
for(int i=0; i <20; i++)
{
arr_non_const[i] = 2 + (i*i);
}

Now declare a constant pointer

const int* arr = arr_non_const;

Is it correct? Is there any other way to do so.
Mar 3 '08 #1
2 3038
On Mar 3, 7:10*pm, Pavan <pavan...@gmail .comwrote:
Hi,
* * I need to create a consant array of larze size but however its
elements can be calculated using an equation, say for example I need
an int arry of 20 elements where each element will be

arr[i] = 2 + (i*i)

But I want arry to be constant. How can I declare such a constant
array without actually defining all the elements?

I could think of one way:
Declare a non const arry

int arr_non_const[20];
for(int i=0; i <20; i++)
{
* *arr_non_const[i] = 2 + (i*i);

}

Now declare a constant pointer

const int* arr = arr_non_const;

Is it correct? Is there any other way to do so.
Yes, you can do it that way and expose just 'arr' to the external code
that is supposed to use that array.

You can make the arr_non_const as a global pointer initialized by a
initializer function call which holds the actual array (either static
storage duration or dynamically allocated to increase lifetime) but in
an unnamed namespace and fill it up with whatever logic you have
(initializer function). Then declare the pointer 'arr' as you have
above as a global one as well but you declare it as extern (as in C++
const variables have internal linkage), so as to be accessible in
other places.
Mar 3 '08 #2
On Mar 3, 4:30 pm, Lionel B <m...@privacy.n etwrote:

[...]
Now one thing you can do is
const int const_arr = [20] = { 2, 3, 6, 11, 18, ... } // you have to
explicitly initialize the array with the 20 elements
As I understood it, the OP explicitly required that the array
elements "... be calculated using an equation", so I suspect
that this would not work for them.
If the equation is known at compile time, it's pretty easy to
write a program which will generate the definition of the array,
with all of its initializers. I do this a lot (although I do
remember having problems with it in one case: the array
contained a couple of million members, and the compiler wouldn't
handle it.)
One technique which might be made to work if the
initialisation function were simple/suitable, would be some
template meta-programming trick, where you get the compiler to
perform the calculation, the canonical example being a
compile-time calculated factorial:
http://en.wikibooks.org/wiki/C%2B%2B...Template_Meta-
Programming#Exa mple:_Compile-time_Factorial
This would be total overkill, though, I suspect.
It's a nice trick for obfuscation, but generating the code with
a separate program is a lot easier and more readable.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Mar 4 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5136
by: richbl | last post by:
Hello all, I have a question about unserializing a single array element from a serialized array. Can this be done, or must I first unserialize the array, and then access the element? For example, given: $data = serialize(array('4.50','0.00','0.00'));
13
27047
by: simondex | last post by:
Hi, Everyone! Does anyone know how to initialize an int array with a non-zero number? Thank You Very Much. Truly Yours, Simon Dexter
7
2714
by: Chris Wertman | last post by:
I am so lost on this one. Dim Ary as Integer = New Integer(4) {0,1,2,3} FAILS with the error: Array initializer has 1 too few elements. So I try Dim Ary as Integer = New Integer(3) {0,1,2,3} Since arrays start at 0 (I am thinking)
3
1283
by: farseer | last post by:
If i have an array of a certain type, is there away of initializing with without knowing it's type? for example (forgive me if some of this is syntactically incorrect) if i have a procedure like this private sub addElements( target() as Object , elemsToAdd () as object ) begin if ( arr is Nothing ) then {initialize with correct type}
12
3867
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that looked sensible, but it didn't work right. Here is a simple example of what I'm trying to accomplish: // I have a hardware peripheral that I'm...
11
3362
by: abhiM | last post by:
I have a struct that has an array in it. I need to assign space to the array in a function and pass the corresponding struct by reference to another function so that it can store values into the array. When I try it with the following code i get these errors 1. Use of possibly unassigned field 'micData' 2. The out parameter 'rem' must be...
3
1926
by: Steve the Pocket | last post by:
So I'm making a heapsort program... all my sort code seems to work just fine. Only problem is, the part where I create the array to test it bombs out whenever the number of elements is over 100. The code is like this... short max; cout << "\nHeapsort Program\n\n"; cout << "Enter # of elements to generate: "; cin >> max; short*...
6
4363
by: Jai Prabhu | last post by:
Hi All, Consider the following piece of code: void func (void) { static unsigned char arr = "\x00\xAA\xBB"; fprintf (stderr, "0x%x\n", arr); fprintf (stderr, "0x%x\n", arr);
8
3450
by: bintom | last post by:
What are the differences between the following methods of declaring strings? char string1 = "C++ forum"; char* string2 = "C++ forum"; I know that the first uses the array notation, whereas the second uses pointer notation. But apart from that what are the implications / dangers, etc. if any.
0
7912
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8216
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.