Solved

Question about Pointers and arrays

Posted on 2004-09-08
7
203 Views
Last Modified: 2010-04-01
Hello. I am currently trying to make a class similar to that of the vector class. I am attempting to make a push_back function. The idea is to have an array of integers of a specified size, say like two ( int array[2] ). The push_back function would then push_back an element into this array. However, if the push_back is called three times, then a NEW array is created with double the space ( int array_two[4] ) and then the elements from the first array, are copied over to the second array. I can achieve this easily. However, I would need the first array to somehow point to the second array, while the first array ELEMENTS were deleted and the second array POINTER were deleted. The result would be a never ending supply of array space, much like a vector. Here is my sample code so far, however, it does not do what I need it to:

void vector<int>::push_back(const int& data)
{
      if(THE_ARRAY_CAPACITY > THE_SIZE_SO_FAR)
      {
            //we have room
            theDataPtr[THE_SIZE_SO_FAR] = data;
            THE_SIZE_SO_FAR++;
      }
      else
      {
            int* TempPtr = new int[(THE_ARRAY_CAPACITY*2)];
            for(unsigned int i = 0; i<THE_ARRAY_CAPACITY; i++)
            {
                  TempPtr[i] = theDataPtr[i];
            }
            THE_ARRAY_CAPACITY = THE_ARRAY_CAPACITY*2
            theDataPtr = TempPtr;
            theDataPtr[THE_SIZE_SO_FAR] = data;
            THE_SIZE_SO_FAR++;
            delete TempPtr;      
      }
}

If there is something wrong with this code, or perhaps another way to do it, help would be GREATLY appreciated.
0
Comment
Question by:mizizike
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 3

Expert Comment

by:teratoma
ID: 12012920
Your code isn't very pretty and has some problems std::vector doesn't have, but I can see only one thing really wrong with it.  See anything wrong with this sequence of events?

 int* TempPtr = new int[(THE_ARRAY_CAPACITY*2)];
 theDataPtr = TempPtr;
 delete TempPtr;  

I'll let you think about it a little...

You just deleted your data :)
0
 
LVL 4

Expert Comment

by:rafd123
ID: 12012959
I **THINK** what a typical implmentation of vector does is when it reaches the capacity of its current underlying array, it allocates a brand new array that's 50% larger than the current array, does a memcopy (or equivelent) of the current array into the new array, deletes the current array, and finally makes the new array the current array.
0
 
LVL 4

Accepted Solution

by:
rafd123 earned 100 total points
ID: 12012995
Sorry...I see now that's pretty much what you're doing; it's late!

teratoma is right...the code should look something like this:

     ...
     else
     {
          int* TempPtr = new int[(THE_ARRAY_CAPACITY*2)];
          for(unsigned int i = 0; i<THE_ARRAY_CAPACITY; i++)
          {
               TempPtr[i] = theDataPtr[i];
          }
          THE_ARRAY_CAPACITY = THE_ARRAY_CAPACITY*2
          delete[] theDataPtr; // deallocate the old array...note this is done with delete[] instead of delete
          theDataPtr = TempPtr; // assign pointer of the new array to the current array
          theDataPtr[THE_SIZE_SO_FAR] = data;
          THE_SIZE_SO_FAR++;    
     }
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Assisted Solution

by:brettmjohnson
brettmjohnson earned 100 total points
ID: 12013054
might I suggest using realloc() instead of new() in this case.
It does exactly what you want.

0
 
LVL 3

Assisted Solution

by:teratoma
teratoma earned 100 total points
ID: 12013184
Ok, now I have to make more comments.

This is someone attmpting to make a generic container, so realloc and memcpy won't work directly, because destructors and constructors won't be called.  It'll work with ints but not in general.  Of course, if mizizike wants to get to that level it's possible because there's in-place new and delete.  Standard containers often take an allocator as a template parameter just so that they don't need to hardcode the allocation strategy.  This is the wave of the future.  But that's not the question at hand.  mizizike is doing the right thing by finding out about the standard containers, but wrote a little bug.  I do it all the time.  Good job mizizike, more power to you, try to be more careful when working on medical technology.

The reason why we multiply by 1.5 instead of 2 is so our growth doesn't challenge our expansion :)  Do a search about the golden ratio.


0
 
LVL 12

Expert Comment

by:stefan73
ID: 12015149
Hi teratoma,
> 1.5 ... the golden ratio
That depends very much on the actual use. Arrays and dynamic strings are small in most case, but when they get bigger, they tend to get really big. I think a 90/10 distribution is realistic in many cases: 10% of all arrays or strings take 90% of the memory.

If you're concerned about memory use in your special case and don't have to write a generic routine, create some statistics as part of a volume test. In case you can't do that, use a constructor with optional growth parameters. Factors are fine for big instances, but constants are usually better.

Cheers!

Stefan
0
 

Author Comment

by:mizizike
ID: 12016212
Wow. Ive used this experts exchange before, but this is the only time I was given the chance to think, plus presented with multiple solutions, and why they should work. I really enjoyed all of the help given to me. To be honest, I am writing a templated vector class, but I thought it would easier in this case of presenting a question, to replace all of the "template <typname T>" with "int" instead. I now understand that this can affect what I am trying to achieve very much. Thanks again for all your help.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question