Jump to content
xisto Community
kharthi

Array Implementation Using C++

Recommended Posts

Hi, I need to implement a class cppArray which is identical to a one dimensional C++ array. It should perform range checking(index set is a set of consecutive integer from 0). It allows only one array to be assigned to another array using = operator. Supports a function that returns the size of an array. It allows reading and printing through use of cout and cin. Immediate response will help out a lot, thanks in advance!

Edited by kharthi (see edit history)

Share this post


Link to post
Share on other sites

Hi,

 

I need to implement a class cppArray which is identical to a one dimensional C++ array. It should perform range checking(index set is a set of consecutive integer from 0). It allows only one array to be assigned to another array using = operator. Supports a function that returns the size of an array. It allows reading and printing through use of cout and cin. Immediate response will help out a lot, thanks in advance!

 


Sizeof array ?

 

string str[] = {"123","456","789"}

cout<<"Array size:"<<sizeof(str)/sizeof(str[0]);

 

output:

Array size:3

 

Is that what you want?

Share this post


Link to post
Share on other sites

So... for the range checking, you could do something likeif (index >= sizeof(str)/sizeof(str[0])) return -1; (error)SizeOf array could be kept as a separate variable.For COUT, you could just forward it to the printf("%s", str); method.Is there anything else?

Share this post


Link to post
Share on other sites

The sizeof operation does work for arrays in C when you use it in the same scope that the array was declared, but the moment you pass the array as a parameter, the array degrades into a pointer and you won't have any way of determining the size other than by passing in the size of the array as a parameter. I am guessing that the compiler can tell what the size of an array is, but the size is not maintained at run time so you have to define a variable to keep track of the size, if you intend to pass the array to a function at some point.In either case, you could drop the use of arrays entirely and use dynamically allocated memory because arrays are typically of a fixed size (ignoring the extensions that some compilers lend to the C language) and if you allocate too much space for an array, you're either wasting space or you will run out of stack space eventually.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.