|
-
Sep 4th, 2002, 08:06 AM
#1
Thread Starter
Lively Member
Need more efficient way to append character arrays
Hey my character array stores a list of items but my implementaion is very inefficient. Here is what I do:
1. I Create a buffer of 100 chars.
2. My function search for the items in a text file.
3. If the list goes over 100 chars then i create new char * and move all the list to the new one.
3. If the list goes over 100 chars then i create new char * and move all the list to the new one.
step 3 is my problem because I'm creating a new buffer for the whole list everytime when the list needs more space.
Is it possible to append the new buffer to the old list, instead of creating a new buffer for the whole list?
Thanx in advance
PS: I can't use linked list because I need to pass the items back to client app.
Last edited by XfoxX; Sep 4th, 2002 at 08:10 AM.
-
Sep 4th, 2002, 09:12 AM
#2
Frenzied Member
Code:
#define SIZE 100
char *buf;
int counter=1;
buf = (char*) malloc(SIZE);
..................
// we need more space
buf = realloc(buf,++counter * SIZE); // add 100 bytes
The new buffer has all the old stuff at the start, plus free space at the end
-
Sep 7th, 2002, 09:17 PM
#3
Thread Starter
Lively Member
realloc will work with new and delete?
thanx again
-
Sep 9th, 2002, 05:40 AM
#4
You shouldn't assume that it does, but it will at least with the MSVC CRT implementation.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Sep 9th, 2002, 07:56 AM
#5
Thread Starter
Lively Member
Two more question, why every c++ book tells you to use new instead of malloc?
Malloc is suitable if the buffer goes over 2000 character?
Thanks
-
Sep 9th, 2002, 08:27 AM
#6
a) Because you don't need to cast the pointer returned from malloc.
b) new knows the size of a type
int *p = new int[100];
is better than
int *p = (int*)malloc(100 * sizeof(int));
c) ONLY new calls object constructors!
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Sep 9th, 2002, 09:52 AM
#7
Frenzied Member
Saying it another way:
new is less prone to errors in typing, and is standard for C++.
You have to use it to create new instances of a class.
For C, malloc or calloc are standard.
You can use realloc for now with MSVC++. Just watch porting it to another compiler.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|