473,672 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help about pointer copy

Hi,

I have an array and I want to adjust the size (remove some elements). I use
the following code. Can you help me to check whether it's correct.

////////////// start
int *p1 = new int[oldsize];

// ....
// set the values of p1

int *p2 = p1;
p1 = new int[newsize];

// copy some values from p2 to p1
for ( i = 0; i .... )
if (....) p1[i] = p2[i];

delete []p2;

////////////// end

Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy way
to reset the length of p1? (e.g, p1 becomes int[20] and the first 10
elements keep the original value).

Thank you very much in advance for your help!

JJ
Jul 22 '05 #1
14 1699
"Jinjun Xu" <jj**@ucla.ed u> wrote...
I have an array and I want to adjust the size (remove some elements). I use the following code. Can you help me to check whether it's correct.

////////////// start
int *p1 = new int[oldsize];

// ....
// set the values of p1

int *p2 = p1;
p1 = new int[newsize];

// copy some values from p2 to p1
for ( i = 0; i .... )
if (....) p1[i] = p2[i];

delete []p2;

////////////// end
Seems fine.
Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy way to reset the length of p1? (e.g, p1 becomes int[20] and the first 10
elements keep the original value).


You don't have to change anything in that case. Just think you have
fewer elements and only use as many as you think there are. And, no,
there is no "easy way to reset the length" of a dynamic array.

Victor
Jul 22 '05 #2
inline...

"Jinjun Xu" <jj**@ucla.ed u> wrote in message
news:c9******** **@daisy.noc.uc la.edu...
Hi,

I have an array and I want to adjust the size (remove some elements). I use the following code. Can you help me to check whether it's correct.

////////////// start
int *p1 = new int[oldsize];

// ....
// set the values of p1

int *p2 = p1;
p1 = new int[newsize];

// copy some values from p2 to p1
for ( i = 0; i .... )
if (....) p1[i] = p2[i];

delete []p2;

////////////// end

Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy way to reset the length of p1? (e.g, p1 becomes int[20] and the first 10
elements keep the original value).

Thank you very much in advance for your help!

JJ


The easy way is to use a vector instead of an array. Arrays have a fixed
size limitation while a vector container dynamically resizes itself.
Additionally, all STL containers come equipped with powerful member
functions, iterators and algorithms to swap, sort, replace, append, push,
pop, etc...

as a simple example using a vector of integers and a display function:

#include <iostream>
#include <vector>

void display(std::ve ctor<int>& r_v)
{
std::cout << "vector contents:" << std::endl;

std::vector<int >::iterator it;
for (it = r_v.begin(); it != r_v.end(); it++)
{
std::cout << *it << std::endl;
}
}

int main()
{
std::vector<int > vi;

// add a few elements
vi.push_back(0) ;
vi.push_back(1) ;
vi.push_back(2) ;

std::cout << "vector vi has " << vi.size() << " elements" << std::endl;
display(vi);

// add more elements
vi.push_back(3) ;
vi.push_back(4) ;
vi.push_back(5) ;

std::cout << std::endl << "vector vi has " << vi.size() << " elements"
<< std::endl;
display(vi);

std::cout << std::endl;

return 0;
}

Jul 22 '05 #3
"Jinjun Xu" <jj**@ucla.ed u> wrote in message news:<c9******* ***@daisy.noc.u cla.edu>...
Hi,

I have an array and I want to adjust the size (remove some elements). I use
the following code. Can you help me to check whether it's correct.

////////////// start
int *p1 = new int[oldsize];

// ....
// set the values of p1

int *p2 = p1;
p1 = new int[newsize];

// copy some values from p2 to p1
for ( i = 0; i .... )
if (....) p1[i] = p2[i];

delete []p2;

////////////// end

Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy way
to reset the length of p1? (e.g, p1 becomes int[20] and the first 10
elements keep the original value).

No, there is not a straightforward way to do this with raw pointers.
However you can do what you want using the STL containers std::vector
or std::deque, which will grow automatically as you add data to them.
They also have functions to ensure you have enough space to hold a
minimum number of elements. However, one caveat is that each time
they grow, any pointers (or other iterators) into the container become
invalid.

HTH, Dave Moore
Jul 22 '05 #4

Thank you guys for the reply and help! It was my first post in news group
and I am so happy to get the answer quickly and helpfully.

It seems that I should spend more time on learning using the classes in the
C++ library instead of writing from scratch by myself. My work is on
numerical computation so I need to use vector and matrix often. What I did
is to write the classes CVector and CMatrix by myself. Now I know that
vector class may help me much. Thank you.

JJ

"SaltPeter" <Sa*******@Jupi ter.sys> wrote in message
news:hI******** **************@ news20.bellglob al.com...
inline...

"Jinjun Xu" <jj**@ucla.ed u> wrote in message
news:c9******** **@daisy.noc.uc la.edu...
Hi,

I have an array and I want to adjust the size (remove some elements). I use
the following code. Can you help me to check whether it's correct.

////////////// start
int *p1 = new int[oldsize];

// ....
// set the values of p1

int *p2 = p1;
p1 = new int[newsize];

// copy some values from p2 to p1
for ( i = 0; i .... )
if (....) p1[i] = p2[i];

delete []p2;

////////////// end

Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy

way
to reset the length of p1? (e.g, p1 becomes int[20] and the first 10
elements keep the original value).

Thank you very much in advance for your help!

JJ


The easy way is to use a vector instead of an array. Arrays have a fixed
size limitation while a vector container dynamically resizes itself.
Additionally, all STL containers come equipped with powerful member
functions, iterators and algorithms to swap, sort, replace, append, push,
pop, etc...

as a simple example using a vector of integers and a display function:

#include <iostream>
#include <vector>

void display(std::ve ctor<int>& r_v)
{
std::cout << "vector contents:" << std::endl;

std::vector<int >::iterator it;
for (it = r_v.begin(); it != r_v.end(); it++)
{
std::cout << *it << std::endl;
}
}

int main()
{
std::vector<int > vi;

// add a few elements
vi.push_back(0) ;
vi.push_back(1) ;
vi.push_back(2) ;

std::cout << "vector vi has " << vi.size() << " elements" <<

std::endl; display(vi);

// add more elements
vi.push_back(3) ;
vi.push_back(4) ;
vi.push_back(5) ;

std::cout << std::endl << "vector vi has " << vi.size() << " elements"
<< std::endl;
display(vi);

std::cout << std::endl;

return 0;
}

Jul 22 '05 #5
On Thu, 03 Jun 2004 09:31:32 +0200, Dave Moore wrote:
However you can do what you want using the STL containers std::vector or
std::deque, which will grow automatically as you add data to them. They
also have functions to ensure you have enough space to hold a minimum
number of elements. However, one caveat is that each time they grow,
any pointers (or other iterators) into the container become invalid.


Would you elaborate on this a little bit. Does "... become invalid" mean
that the order and offset of the specific elements in the vector could
change and therefor the pointers/iterators become invalid or does it mean
that the order and offset of the vector-elements keep the same when adding
(push_back()) to a vector and just the references become invalid due to
some vector-internal management ?

Thanks in advance for your answer.

Darius.
Jul 22 '05 #6
> It seems that I should spend more time on learning using the classes in
the
C++ library instead of writing from scratch by myself. My work is on
numerical computation so I need to use vector and matrix often. What I did
is to write the classes CVector and CMatrix by myself. Now I know that
vector class may help me much. Thank you.


Try then Newmat library from http://www.robertnz.net/nm_intro.htm

Jul 22 '05 #7
Jinjun Xu posted:
Suppose I have an array, e.g., int *p1 = new int[10]; is there any easy
way to reset the length of p1? (e.g, p1 becomes int[20] and the first
10 elements keep the original value).

Imagine that this is your int[10] in memory:
char double int int int int int int int int int int char double int*
unsigned short int
What I'm getting at is that your int[10] may be boxed-in in memory. Thus,
you're *not guaranteed* that you can make it bigger! You'll have to find an
unused bit of memory of length int[20] and move your values.
-JKop
Jul 22 '05 #8
> On Thu, 03 Jun 2004 09:31:32 +0200, Dave Moore wrote:
However you can do what you want using the STL containers std::vector or
std::deque, which will grow automatically as you add data to them. They
also have functions to ensure you have enough space to hold a minimum
number of elements. However, one caveat is that each time they grow,
any pointers (or other iterators) into the container become invalid.
Would you elaborate on this a little bit. Does "... become invalid" mean
that the order and offset of the specific elements in the vector could
change and therefor the pointers/iterators become invalid or does it mean
that the order and offset of the vector-elements keep the same when adding
(push_back()) to a vector and just the references become invalid due to
some vector-internal management ?


When you push_back(), the indices of the existing elements remain the
same, however, the iterators become invalid because the elements might
be moved. Consider reserve().

Thanks in advance for your answer.
You're welcome Darius.


!!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!
To iterate is human, to recurse divine.
-L. Peter Deutsch
!!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!
Jul 22 '05 #9
"Darius.Moo s AT esigma-systems DOT de" <pf*********@gm x.de> wrote in message news:<2i******* *****@uni-berlin.de>...
On Thu, 03 Jun 2004 09:31:32 +0200, Dave Moore wrote:
However you can do what you want using the STL containers std::vector or
std::deque, which will grow automatically as you add data to them. They
also have functions to ensure you have enough space to hold a minimum
number of elements. However, one caveat is that each time they grow,
any pointers (or other iterators) into the container become invalid.


Would you elaborate on this a little bit. Does "... become invalid" mean
that the order and offset of the specific elements in the vector could
change and therefor the pointers/iterators become invalid or does it mean
that the order and offset of the vector-elements keep the same when adding
(push_back()) to a vector and just the references become invalid due to
some vector-internal management ?

Thanks in advance for your answer.


Well, the terse answer is that they become invalid because the
Standard says so ... I guess the correct way to interpret this is that
the Standard places no restrictions on compiler developers to make
sure that they remain valid, as it does with (for example) std::list.
What that means in the end is that, it doesn't really matter *how*
they become invalid, but rather that you can no longer rely on them to
behave in the correct way.

Sorry if this is a somewhat unsatisfying answer, but I don't really
know the guts of the STL containers, only (some of) what is in the
Standard, which is all that is required for users. There are good
books and websites to help you learn more about implementation details
if you are interested ... try www.accu.org for more info.

As far as your examples are concerned, I think that either of your
suggestions above might be a (partial) answer for a particular
implementation. Note however that if you start relying on a
particular behavior for something that is specified as undefined (or
even implementation-defined), then somewhere down the line your code
is probably going to break.

HTH, Dave Moore
Jul 22 '05 #10

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

Similar topics

2
2034
by: dinks | last post by:
Hi, I'm new to C++ and have been assigned a task which i dont completely understand. Any help would be greately appreciated. Here is the problem: The class "linkedListType" use the "assert" facility. I am to get rid of them and replace them with exceptions. I need to create a "linkedListException" class that's declared and implemented in my "linkedListType" class. This class needs to inherit from the base "exception" class and return...
4
2244
by: xuatla | last post by:
Hi, How to copy a pointer to another pointer? Can I do in the following way: // START double *copyfrom = new double; double *copyto = new double;
5
2098
by: jhon02148 | last post by:
hi this hw have four files: 1. for the main program 2. listp.cpp (the source file) 3. listp.h (the header file) 4. exception.h if there is anybody who could help me with this hw i really appreciate his help. thanks for anybody in advance
1
2016
by: jhon02148 | last post by:
hi this hw have four files: 1. for the main program 2. listp.cpp (the source file) 3. listp.h (the header file) 4. exception.h hi iam done with my hw i still have to do one function which is the last one on program.cpp subsetsum(int aList, int sum)so please can you help.
23
2234
by: Brian | last post by:
I am very new to C# programming and have run into a problem. I apologize for the repost of this article. For some reason, my news reader attached it to an existing thread. First off, I have an SDK that I have written for C/C++ and would like to port it to C# if at all possible. Basically, I've got a structure that I need to pass to the C-style DLL (i.e. no mangled names - everything is __stdcall). This structure needs
13
4917
by: ern | last post by:
I'm using strtok( ) to capture lines of input. After I call "splitCommand", I call strtok( ) again to get the next line. Strtok( ) returns NULL (but there is more in the file...). That didn't happen before 'splitCommands' entered the picture. The problem is in splitCommands( ) somehow modifying the pointer, but I HAVE to call that function. Is there a way to make a copy of it or something ? /* HERE IS MY CODE */ char *...
14
2408
by: key9 | last post by:
Hi All On coding , I think I need some basic help about how to write member function . I've readed the FAQ, but I am still confuse about it when coding(reference / pointer /instance) , so I think I need some "template". Sorry for my coding experience in c++
8
2932
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, I'm using vs2005, .net 2, C# for Windows application. I use DllImport so I can call up a function written in C++ as unmanaged code and compiled as a dll us vs2005. My application is able to call the function, EncodeAsnUser. And it's returning OK but when I display the decoded data in another part of my application it shows no data has been decoded, all fiedls are either null or blanks. For some reason, I am not able to step through...
3
2306
by: Stephen Torri | last post by:
Below is a class that is suppose to represent a segment of memory or a contents of a binary image (e.g. ELF executable). I have started to read Modern C++ Design and thought the best way to ensure I was understanding the chapter on policy classes was to attempt to apply them to my project. I understand the general concept of policies but I lack the knowledge and wisdom of how to identify them in an existing project. So I figured to get an...
30
2454
by: Alf P. Steinbach | last post by:
I once suggested in that SomeOne Else(TM) should propose a string value class that accepted literals and char pointers and so on, with possible custom deleter, and in case of literal strings just carrying the original pointer. In other words, for the simplest usage code: * no overhead (just carrying a pointer or two), and * no possibility of exceptions (for that case).
0
8840
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8630
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8694
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7458
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5718
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
4237
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
4434
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2833
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
1831
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.