473,554 Members | 2,315 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

an interesting problem in c

Hi Everyone,

I have the following structure in my program

struct sample
{
char *string;
int string_len;
};

struct sample **ptr; //serves as two-dimentional array

Now, based on run-time input, i will be allocating the memory for ptr
such that i have a 1d array of pointers to structure sample, and each
member will be holding a string, now the problem i have is that the
following is the run time input, say in a file,

string1
string2
string3

now, i need to allocate ptr to hold three set of struct sample and
store each of the string in one member's string (after allocation),
something like

struct sample ptr = (struct sample**)malloc (<value>*sizeof (struct
sample*));
for(i=0;i<value ;i++)
{
struct sample ptr[i] = (struct sample*)malloc( sizeof(struct sample));
sample[i].string = (char*)malloc(1 00); //each will hold the string
}
The problem i'm facing is that i don't know the value in advance
(which i will know only after the end of the file), please give me any
suggestions as to how to do it?

Dec 19 '06 #1
22 1886
sa*****@yahoo.c o.in wrote:
I have the following structure in my program

struct sample {
char *string;
int string_len;
};

struct sample **ptr; //serves as two-dimentional array

Now, based on run-time input, i will be allocating the memory for ptr
such that i have a 1d array of pointers to structure sample, and each
member will be holding a string, now the problem i have is that the
following is the run time input, say in a file,

string1
string2
string3

now, i need to allocate ptr to hold three set of struct sample and
store each of the string in one member's string (after allocation),
something like

struct sample ptr = (struct sample**)malloc (<value>*sizeof (struct sample*));
for(i=0;i<value ;i++) {
struct sample ptr[i] = (struct sample*)malloc( sizeof(struct sample));
sample[i].string = (char*)malloc(1 00); //each will hold the string
}

The problem i'm facing is that i don't know the value in advance
(which i will know only after the end of the file), please give me any
suggestions as to how to do it?
I've written an entire library that solves this exact problem (and
others.) You can read about it here:

http://bstring.sf.net/

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 19 '06 #2

sa*****@yahoo.c o.in wrote:
Hi Everyone,

I have the following structure in my program

struct sample
{
char *string;
int string_len;
};

struct sample **ptr; //serves as two-dimentional array

Now, based on run-time input, i will be allocating the memory for ptr
such that i have a 1d array of pointers to structure sample, and each
member will be holding a string, ...
[snip]
The problem i'm facing is that i don't know the value in advance
(which i will know only after the end of the file), please give me any
suggestions as to how to do it?
You could look at something involving realloc() - allocating an initial
reasonable value for the array of pointers and increasing by a suitable
factor when it overflows.

You could look at a two-pass approach - either read the file once to
determine how much data you have, size the array and then read again;
or read the data initially into a different structure - say a linked
list - and transform it to an array once you have all the data.

Dec 19 '06 #3
>
You could look at something involving realloc() - allocating an initial
reasonable value for the array of pointers and increasing by a suitable
factor when it overflows.

You could look at a two-pass approach - either read the file once to
determine how much data you have, size the array and then read again;
or read the data initially into a different structure - say a linked
list - and transform it to an array once you have all the data.
I can't afford parsing the file two times and neither can i have a
temp list to hold all the values, first one is costly from time
prespective and second one is costly from memory prespective... so i
guess i'm left out with only realloc(), i have never used one... does
it make sure that old block's values are retained when i decide to
re-alloc?

Dec 19 '06 #4
sa*****@yahoo.c o.in said:

<snip>
I can't afford parsing the file two times and neither can i have a
temp list to hold all the values, first one is costly from time
prespective and second one is costly from memory prespective... so i
guess i'm left out with only realloc(), i have never used one... does
it make sure that old block's values are retained when i decide to
re-alloc?
Yes, even if the reallocation fails and realloc returns NULL (which it
might).

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 19 '06 #5
>
Yes, even if the reallocation fails and realloc returns NULL (which it
might).
Do you mean, even if re-alloc fails due to memory shortage, it would
return NULL and it wouldn't disturb the old memory which was previously
allocated?

Dec 19 '06 #6
sa*****@yahoo.c o.in said:
>
>>
Yes, even if the reallocation fails and realloc returns NULL (which it
might).

Do you mean, even if re-alloc fails due to memory shortage, it would
return NULL and it wouldn't disturb the old memory which was previously
allocated?
Correct. BUT that does require a little effort on your part, if you don't
want to lose track of that old memory.

#include <stdlib.h>

int main(void)
{
int *tmp = NULL;
size_t n = 1024;

int *p = malloc(n * sizeof *p);
if(p != NULL)
{
int i;
for(i = 0; i < n; i++)
{
p[i] = i;
}
/* now let's try to get some more memory */
n *= 2;
tmp = realloc(p, n * sizeof *p);
if(tmp == NULL)
{
/* the allocation FAILED, but because we used tmp to detect
this, we can still get to the old block, using p, which
still points to the old block.
*/
}
else
{
/* the allocation SUCCEEDED. p is now invalid, but we can
safely fix that now:
*/
p = tmp;
while(i < n)
{
p[i] = i;

etc etc etc
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 19 '06 #7

sa*****@yahoo.c o.in wrote:
Hi Everyone,

I have the following structure in my program

struct sample
{
char *string;
int string_len;
};

struct sample **ptr; //serves as two-dimentional array

Now, based on run-time input, i will be allocating the memory for ptr
such that i have a 1d array of pointers to structure sample, and each
member will be holding a string, now the problem i have is that the
following is the run time input, say in a file,

string1
string2
string3

now, i need to allocate ptr to hold three set of struct sample and
store each of the string in one member's string (after allocation),
something like

struct sample ptr = (struct sample**)malloc (<value>*sizeof (struct
sample*));
for(i=0;i<value ;i++)
{
struct sample ptr[i] = (struct sample*)malloc( sizeof(struct sample));
sample[i].string = (char*)malloc(1 00); //each will hold the string
}
The problem i'm facing is that i don't know the value in advance
(which i will know only after the end of the file), please give me any
suggestions as to how to do it?
member will be holding a string, now the problem i have is that the
following is the run time input, say in a file,

string1
string2
string3

now, i need to allocate ptr to hold three set of struct sample and
store each of the string in one member's string (after allocation),
something like

struct sample ptr = (struct sample**)malloc (<value>*sizeof (struct
sample*));
for(i=0;i<value ;i++)
{
struct sample ptr[i] = (struct sample*)malloc( sizeof(struct sample));
sample[i].string = (char*)malloc(1 00); //each will hold the string
}

The problem i'm facing is that i don't know the value in advance
(which i will know only after the end of the file), please give me any
suggestions as to how to do it?
The best strategy will depend on the characteristics of typical input.

If possible, one option is to read the input twice, once to count the
number of string pointers needed and a second time to input them and
set the pointers into your dynamic array.

If the input can be read more than once, another option is to count the
number of strings and also accumulate the total number of characters in
them on the first run. Before the second run the pointer array is
allocated for the number of strings plus one and a single array of
characters is allocated for the total number of characters (you might
also want the nul terminators as well).

Then as the strings are read in they are placed 'end to end' in the
large character array and their start positions are recorded in the
pointer array. At the end the last pointer is set to one past the top
of the character array. Now the strings are contained between
consecutive pointer values. This avoids the overhead of many individual
memory allocations for each of the strings and simplifies the memory
allocation and deallocation tasks.

But if the input can only be read once you may need to allocate for a
fixed number of pointers and then to input strings until either the end
of the input or this number is reached. If the pointer array becomes
full before the end of file you can then use realloc() to obtain a
larger block of memory for your structure whilst preserving the
previous values you have set (the block might move but the values are
preserved).

How much to memory to allocate initially for pointers and how expand
the block each time you fill it will again depend on the typical
characteristics of your inputs.

Cactus

Dec 19 '06 #8

sa*****@yahoo.c o.in wrote:

You could look at something involving realloc() - allocating an initial
reasonable value for the array of pointers and increasing by a suitable
factor when it overflows.

You could look at a two-pass approach - either read the file once to
determine how much data you have, size the array and then read again;
or read the data initially into a different structure - say a linked
list - and transform it to an array once you have all the data.

I can't afford parsing the file two times and neither can i have a
temp list to hold all the values, first one is costly from time
prespective and second one is costly from memory prespective...
The same set of structures can be members both of the linked list and
the array, of course...

Dec 19 '06 #9
>
#include <stdlib.h>

int main(void)
{
int *tmp = NULL;
size_t n = 1024;

int *p = malloc(n * sizeof *p);
if(p != NULL)
{
int i;
for(i = 0; i < n; i++)
{
p[i] = i;
}
/* now let's try to get some more memory */
n *= 2;
tmp = realloc(p, n * sizeof *p);
if(tmp == NULL)
{
/* the allocation FAILED, but because we used tmp to detect
this, we can still get to the old block, using p, which
still points to the old block.
*/
}
else
{
/* the allocation SUCCEEDED. p is now invalid, but we can
safely fix that now:
*/
p = tmp;
while(i < n)
{
p[i] = i;

etc etc etc
--
I see what you are trying to say, to consider the return value of
re-alloc() when it is successful and when it fails, stick to the old
pointer. And i' m trying to understand as to how re-alloc() works, does
it try to allocate memory at the end of the current chunk and if it
can't do because memory next to current chunk is not free, it would
allocate a whole new block to hold old value and copies old value to
new block making sure new memory is good enough to satisfy the memory
request and free the old block...

Is my understanding correct?

Dec 19 '06 #10

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

Similar topics

8
1670
by: Bruno R. Dias | last post by:
Perhaps it would be interesting to program a virtual machine simulating an ancient computer (such as the pdp-7). Then, it would be rather interesting to code for it (porting gcc to it maybe?). I think it would be fun to play with the long-forgotten art of coding in machine language. And what about a fictional computer, such as one that works...
12
1635
by: rawrite | last post by:
I am just finishing watching a documentary about Rod Serling. It was cool, but after 20 minutes it got boring and all I wanted to do is subscribe to Net Flix and rent the Twilight Zone episodes. Some times the work is more interesting than the life.
3
1624
by: Johnny Lee | last post by:
Hi, Look at the follow command in python command line, See what's interesting?:) >>> class A: i = 0 >>> a = A() >>> b = A() >>> a.i = 1 >>> print a.i, b.i
2
4929
by: Dylan Phillips | last post by:
A strang error is occurring when I run the following code: SqlConnection c = new SqlConnection(); c.ConnectionString = "Initial Catalog=Northwind;user id=sa;password=kat1ie;Data Source=server"; c.Open(); SqlCommand command = c.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "select Customers.customerid,...
3
1555
by: eBob.com | last post by:
Is there a namespace of interesting and important constants such as maximum length of a filename, maximum length of a path, maximum and minimum values which can be held by a Long (and other data types of course), etc., etc.? In C there is a header file (I forget its name at the moment) with things like MAX_PATH. Most useful. I know...
8
7958
by: Mythran | last post by:
Here is some code the provides some really interesting results! First, read over the two methods in class 'A' and compare. Just by looking at them, both results appear to return the EXACT same information the same way. But the appearances are deceiving! Copy and paste into a console application, then set the configuration to Release mode...
28
2511
by: v4vijayakumar | last post by:
#include <string> #include <iostream> using namespace std; int main() { string str; str.resize(5); str = 't';
126
4299
by: jacob navia | last post by:
Buffer overflows are a fact of life, and, more specifically, a fact of C. All is not lost however. In the book "Value Range Analysis of C programs" Axel Simon tries to establish a theoretical framework for analyzing C programs. In contrast to other books where the actual technical difficulties are "abstracted away", this books tries to...
4
2622
by: timer | last post by:
In the years past, there used to very interesting discussions in c.l.c But now, topics are not as interesting anymore. What happened?
0
7612
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7536
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7814
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7576
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...
0
6163
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...
0
5165
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...
0
3583
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...
1
2027
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
1
1147
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.