473,414 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

Create a variable size but non-growable array

Hi,

In STL, can I create a variable size but non-growable array?

In Java, I can do this:

int[] void f (int size) {
int[] array = new int[size];
// do something with array
return array;
}

I guess I can use vector<> for that, but I don't need the array to be
growable, I just don't know the size upfront. So I am looking for a
more efficient data structure.

Thank you.

Jan 11 '06 #1
17 2997
yi*****@gmail.com wrote:
In STL, can I create a variable size but non-growable array?
Not in STL. In C++.
In Java, I can do this:

int[] void f (int size) {
int[] array = new int[size];
// do something with array
return array;
}
In C++ you do

int* void f(int size) {
return new int[size];
}
I guess I can use vector<> for that,
But std::vector has exactly the opposite purpose: it's _growing_ as
needed.
but I don't need the array to be
growable,
Dynamic arrays are never "growable".
I just don't know the size upfront. So I am looking for a
more efficient data structure.


To do what?

V
Jan 11 '06 #2
yi*****@gmail.com wrote:
Hi,

In STL, can I create a variable size but non-growable array?
You can do that even with C++. Use dynamic memory allocation
In Java, I can do this:

int[] void f (int size) {
<OT> Aside, A function cannot have _two_ return types - not even in
Java </OT>
int[] array = new int[size];
// do something with array
return array;
}
int C++ you have
int* f(int size)
{
int * array = new int[size];
return array;
}

Note : you need to take care of freeing array exactly once.

I guess I can use vector<> for that, but I don't need the array to be
growable, I just don't know the size upfront. So I am looking for a


Make sure wherether
1) You donot _need_ the array to be growable
2) You donot _want to allow_ the array to be growable.

unless it is second case, std::vector is preferable

Jan 11 '06 #3
Okay, thanks for the help.

Suppose I do this in c++:
int* f(int size)
{
int * array = new int[size];
return array;

}

Is there a safe idiom to prevent memory leak? Should i use auto_ptr in
C++?
Or should I use other smart pointer template in other libraries?

Thank you.

Jan 11 '06 #4
auto_ptr not suitable for the pointer of array
try scoped_array of boost library

Jan 11 '06 #5
yi*****@gmail.com wrote:
Suppose I do this in c++:
int* f(int size)
{
int * array = new int[size];
return array;

}

Is there a safe idiom to prevent memory leak? Should i use auto_ptr in
C++?


You can write a RAII wrapper similar to this:

template<class T> class Array {
T* data;
public:
Array(int sz) : data(new T[sz]) { }
~Array()
{
delete[] data;
}
// define CC, operator=, operator[] and other operators that are
necessary
// decide whether you want a shallow or a deep copy for CC and
operator=
};
Array<int> foo(int size)
{
return Array<int>(size);
}

int main()
{
Array<int> p = foo(5);
} // ~Array<int> for p automatically called.

Jan 11 '06 #6
Thanks.

The reason I ask this question is from what I read in c++ primer 3rd
edition, it said non-const variable size array is illegal.

Page 114 C++ Primer:

The following are examples of both legal and illegal array definitions:

// both buf_size and max_files are const
const int buf_size = 512;
int staff_size = 27;

// ok: const variable
char input_buffer[ buf_size];

// error: non-const variable
double salaries[ staff_size];

Jan 11 '06 #7

ying...@gmail.com wrote:
Thanks.

The reason I ask this question is from what I read in c++ primer 3rd
edition, it said non-const variable size array is illegal.
What this means is that when you declare an array, the size must be
known at compile time. What we are doing in your example is allocating
a chunk of memory (which is guaranteed to be contiguous) and accessing
it through operator[], since a[i] is a syntactic sugar for *(a+i)

Note that when we say
int * arr = new int[10];

arr is simply an integer pointer - it is _not_ an array name. We can
make arr point to somewhere else :
int k;
arr=&k; // works

such assignment would not have been possible had arr been an array
name.
The following are examples of both legal and illegal array definitions:

// both buf_size and max_files are const
const int buf_size = 512;
int staff_size = 27;

// ok: const variable
char input_buffer[ buf_size];

// error: non-const variable
double salaries[ staff_size];


since staff_size is not a compile time constant, this is illegal.

Jan 11 '06 #8
Thanks for your clear explanation.

Jan 11 '06 #9
Thanks for your response.

Jan 11 '06 #10
Neelesh Bodas wrote:
You can write a RAII wrapper similar to this:

template<class T> class Array {
T* data;
public:
Array(int sz) : data(new T[sz]) { }
~Array()
{
delete[] data;
}
// define CC, operator=, operator[] and other operators that are
necessary
// decide whether you want a shallow or a deep copy for CC and
operator=
};


Unless you want a shallow copy, isn't this exactly what std::vector does?

Martin
Jan 11 '06 #11

Martin Vejnar wrote:
Neelesh Bodas wrote:
You can write a RAII wrapper similar to this:


Unless you want a shallow copy, isn't this exactly what std::vector does?


Yes. std::vector is preferrable unless OP wants to _explicitly
disallow_ all other features that std::vector provides (one of them
being push_back)

Jan 11 '06 #12
Thanks. But why I can't use the auto_ptr in c++?
If not, can I use one of the smart pointer from Boost library?

Jan 11 '06 #13

<yi*****@gmail.com> skrev i meddelandet
news:11**********************@o13g2000cwo.googlegr oups.com...
Okay, thanks for the help.

Suppose I do this in c++:
int* f(int size)
{
int * array = new int[size];
return array;

}

Is there a safe idiom to prevent memory leak? Should i use auto_ptr
in
C++?


No, you should use std::vector. :-)

Once you set the vector to the proper size, it stays that size. And it
will manage its own memory.
Bo Persson
Jan 11 '06 #14
yi*****@gmail.com wrote:
Thanks. But why I can't use the auto_ptr in c++?
Because auto_ptr wraps a "pointer to an object", not a "pointer to an
array"
If not, can I use one of the smart pointer from Boost library?


boost::scoped_array

Jan 11 '06 #15
Neelesh Bodas wrote:
yi*****@gmail.com wrote:
Hi,

In STL, can I create a variable size but non-growable array?

You can do that even with C++. Use dynamic memory allocation

Yes and no. You have a pointer to dynamically allocated block of memory
that in almost all cases acts like an array of that type and size. It
will almost certainly satisfy the OP's needs.

It's not a true variable-size array, which is something that was added
to C in the C99 standard. C has more need of it because they don't have
standard containers like vector.

Brian
Jan 11 '06 #16

yi*****@gmail.com wrote:
Hi,

In STL, can I create a variable size but non-growable array?

In Java, I can do this:

int[] void f (int size) {
int[] array = new int[size];
// do something with array
return array;
}

I guess I can use vector<> for that, but I don't need the array to be
growable, I just don't know the size upfront. So I am looking for a
more efficient data structure.


You could always do something like this:

template<typename T>
class array
{
T * arr;
int sz;
public:
array(int x) { arr = new T[x]; sz = x; }
~array() { delete [] arr; }
T & operator[](int i) { return arr[i]; }
int size() { return sz; }
};

That is of course a very simplistic version but it meets the stated
requirements and is relatively safe to use. You would want to add copy
and assignment ops to meet the rule of three but on the other hand this
class can be used as an array of sorts in a memcpy:

memcpy(&a1[0], &a2[0], a2.size() * sizeof(a2[0]));

But this is just as dangerous as doing so with your basic dyn array.
The benefit of using operators would be that you can do some checks and
throw up if the op would result in a buffer overrun. Also, passing by
value would be very ill advised without those operators; would result
in a crash.

Jan 11 '06 #17
On 2006-01-11 16:23:46 -0500, ro**********@gmail.com said:

yi*****@gmail.com wrote:
Hi,

In STL, can I create a variable size but non-growable array?

In Java, I can do this:

int[] void f (int size) {
int[] array = new int[size];
// do something with array
return array;
}

I guess I can use vector<> for that, but I don't need the array to be
growable, I just don't know the size upfront. So I am looking for a
more efficient data structure.


You could always do something like this:

template<typename T>
class array
{
T * arr;
int sz;
public:
array(int x) { arr = new T[x]; sz = x; }
~array() { delete [] arr; }
T & operator[](int i) { return arr[i]; }
int size() { return sz; }
};


Don't forget a copy constructor and assignment operator (rule of 3)
--
Clark S. Cox, III
cl*******@gmail.com

Jan 12 '06 #18

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

Similar topics

0
by: Shashikant Khandelwak | last post by:
Hi ! I am trying to install oracle 9i Standard edition on a windows 2000 SP4 machine. I get through the entire installation up to running the Database Configuration Assistant. While it tries to...
7
by: Bil Muh | last post by:
Esteemede Developers, I would like to Thank All of You in advance for your sincere guidances. I am developing a software using Visual C++ .NET Standard Edition with Windows Form (.NET)...
6
by: SamIAm | last post by:
Hi am creating a email application that needs to mail out a very large amount of emails. I have created a multithreaded c# application that using message queuing. I have created a threadpool of 5...
1
by: John_H | last post by:
Re: ASP.NET 2.0 I would like suggestions or code examples on how to collect a variable length list of input data (item# & item quantity specifically). I thought that I could accomplish this...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
7
by: Jimakos Bilakis | last post by:
Hi guys! I'm using the C++ Builder 6 Enterprise Edition where I create some tables in Paradox and with the help of a structure i pass my data from the form (Edit boxes) to the Paradox table with...
19
by: Manish Tomar | last post by:
Hi All, The following code as per my knowledge should not work: int* some() { int b = 10; return &b; }
3
by: Wijaya Edward | last post by:
Hi, How can we slurp all content of a single file into one variable? I tried this: <open file 'somefile.txt', mode 'r' at 0xb7f532e0>
3
by: John Shell | last post by:
Hello, all. The following code results in a C2666 error (2 overloads have similar conversions). class FSVec2D { public: FSVec2D() { // code omitted }
14
RMWChaos
by: RMWChaos | last post by:
Firebug is reporting "too much recursion" when I attempt to create a child element in a parent that doesn't exist yet. The script should automatically create the missing parent before going on to...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
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...

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.