473,831 Members | 2,306 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arrays of Variable Sizes

For a school assignment I need to write a class to work with the
following code. The IntArray b(-3, 6) basically means that I need to
produce an array of integer values that has an index going from -3 to
6. I'm completely lost on how I should create that array. Any shoves
in the right direction would be appreciated.

void test2()
{
system("cls");
cout << "2. Array declared with two integers: IntArray b(-3, 6);" <<
endl << endl;
csis << "2. Array declared with two integers: IntArray b(-3, 6);" <<
endl << endl;
IntArray b(-3, 6);
for(int i = b.low(); i <= b.high(); i++)
b[i] = i * 10;
b.setName('b');
cout << b << endl;
csis << b << endl;
wait();
}
Jul 19 '05
11 2322
Comments below.

"- Steve -" <se****@foundat ion.sdsu.edu> wrote in message
news:cb******** *************** ***@posting.goo gle.com...
Okay Scratch all that, I've made some major progress. Take a look at this.
class IntArray
{
private:
int arrayLow, arrayHigh; //low & high index of array
char name; //name of object
Do arrays really need names? And why only a single char for the name?
int *array; //pointer to beggining of array

public:
IntArray(); //Constructor - create array index 0-9
IntArray(int); //Constructor for arrays starting at 0
IntArray(int, int); //Constructor for arrays not starting at 0
IntArray(IntArr ay*); //Constructor for making copy of another IntArray object

Not correct. For a copy constructor you (almost) always write

IntArray(const IntArray&);

then you also need assignment operator

IntArray& operator=(const IntArray&);

Without these two you program will crash, because the copielr will generate
these for you, if you haven't written then yourself. But the compiler
generated version will be incorrect because it will copy your array pointer
instead of allocating more memory.

~IntArray(); //Default Deconstructor

int& IntArray::opera tor[](int); //Overload [] for Assigning Values
IntArray:: is incorrect (but some compilers allow it)

int& operator[](int); //Overload [] for Assigning Values

You also need an overload for accessing values from a const array

int operator[](int) const;

int low() {return arrayLow;} //Returns lowest index of array
int high() {return arrayHigh;} //Returns highest index of array
These should be const, its very important in C++ to mark methods as const if
that is what they are

int low() const {return arrayLow;} //Returns lowest index of array
int high() const {return arrayHigh;} //Returns highest index of array

Without the const methods I've described above, this code would not compile

int print_array(con st IntArray& a)
{
for (int i = a.low(); i <=a.high(); ++i)
cout << a[i];
}

because a is a const.

void setName(char myName) {name=myName;} //Sets name of object
};

#include "intarray.h "

IntArray::IntAr ray()
{
arrayLow=0;
arrayHigh=9;

array=new int[arrayHigh-arrayLow];
}

IntArray::IntAr ray(int size)
{
arrayLow=0; //array starts at 0
arrayHigh=size-1; //highest index of array based on given size

array=new int[size]; //create array memory locations
}

IntArray::IntAr ray(int low, int high)
{
arrayLow=low; //start of array index
arrayHigh=high; //end of array index

if(arrayLow==ar rayHigh)
array=new int[1]; //if high and low are equal create an array 1 unit long
else
array=new int[arrayHigh-arrayLow]; //create array memory locations
The math is wrong

array=new int[(arrayHigh - arrayLow) + 1];

No need to treat low == high as a special case (this should have been a
warning that you'd got something wrong, specail cases are to be avoided if
possible).
}

IntArray::IntAr ray(IntArray* copyThis)
{
arrayLow=copyTh is->low();
arrayHigh=copyT his->high();

if(arrayLow==ar rayHigh)
array=new int[1]; //if high and low are equal create an array 1 unit long
else
array=new int[arrayHigh-arrayLow]; //create array memory locations
Again the math is wrong, but the basic idea is right. Now rewrite this to
use the proper method of writing a copy constructor. The don't forget to add
an assignment operator.

for(int i=arrayLow;i<=a rrayHigh;i++)
array[i]=copyThis->array[i];
}

IntArray::~IntA rray()
{
//for(int i=arrayLow;i<=a rrayHigh;i++)
// delete [] array[i];
//delete [] array;
delete[] array; is correct.
}

int& IntArray::opera tor[] (int forLocation)
{
return array[arrayLow+forLoc ation];
}

Also some quick requirments:

IntArray a(10), w(10); // Ten elements, indexed 0 to 9
IntArray b(-3, 6); // Ten elements, indexed -3 to 6
IntArray c(6, 8); // Three elements, indexed 6 to 8
IntArray d(5, 5); // Single element array, indexed at 5
IntArray z; // Ten elements, indexed 0 to 9


Looks pretty good. You've made the common newbie mistakes, ignoring the
issue of const, and being unsure about copying, but you're not far away from
finishing this.

john
Jul 19 '05 #11
Another math error

IntArray::IntAr ray()
{
arrayLow=0;
arrayHigh=9;

array=new int[arrayHigh-arrayLow];


array = new[(arrayHigh-arrayLow)+1];

or rether more simply

array = new[10];

BTW you obviously haven't heard of initaliser lists. Really all your
constructors should be written like this

IntArray::IntAr ray() : arrayLow(0), arrayHigh(9), array(new int[10])
{
}

Look them up in your favourite C++ book.

john
Jul 19 '05 #12

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

Similar topics

5
2558
by: Cant Think Today | last post by:
I have multi-dimesional arrays that can be specifed by the user, e.g 1,2,3,4,5 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6 I think a bit of code that will iterate over these arrays to print out the element indices for each unique element in the N-dimensional array. E.g. for the above
12
1994
by: Samee Zahur | last post by:
Back in the days of old C, only numeric literals could be used as dimensions for statically allocated arrays - the size had to be resolved to a constant at/before compile time. Now I'm beginning to suspect(!) that this is no longer the case either with C or with C++ :( Can anyone upgrade me with the present state/version of rules? (for C++) Exactly, by how many years am I back-dated ???
79
3442
by: Me | last post by:
Just a question/observation out of frustration. I read in depth the book by Peter Van Der Linden entitled "Expert C Programming" (Deep C Secrets). In particular the chapters entitled: 4: The Shocking Truth: C Arrays and Pointers Are NOT the Same! 9: More about Arrays 10: More about Pointers What blows me out of the water is the fact that 'every' programmer
9
1635
by: Merrill & Michele | last post by:
What follows is an adaptation of the second program in K&R §5.10. The changes are to elucidate (validate) the difference (sameness) of char * and char**. I cannot for the life of me understand why the output looks the way it does, in particular, with all the symmetry in arguments, why one sees apple but not argv. This program was designed to run from a command line with one argument (two if you count the prog name). The .c file...
11
4478
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to accomplish. // - - - - - - - - begin code - - - - - - - typedef int sm_t; typedef int bg_t; sm_t sm; bg_t bg;
39
19662
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1) What's the difference between these 3 statements: (i) memcpy(&b, &KoefD, n); // this works somewhere in my code
11
1959
by: Sunny | last post by:
#include <iostream> int main() { int len; std::cin >len; int Arr; int *p = new int; Arr=5; std::cout << &len << " " << &Arr << " " << p << std::endl;
7
4517
by: daniel | last post by:
Hello , I always had the feeling that is better to have char arrays with the size equal to a power of two. For example: char a_str; // feels ok char b_str; //feels not ok.
4
5863
by: Edward Jensen | last post by:
Hi, I have the following static arrays of different size in a class: in header: static double w2, x2; static double w3, x3; static double w4, x4; in GaussLegendre.cpp:
0
9793
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9642
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10777
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5619
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4416
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3963
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3076
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.