473,835 Members | 2,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

realloc'ing an array of strings

I'm trying (struggling) to use realloc to grow a list of strings. The
number of strings is not known (this is a subset of an assignment to write a
recursive ls program... my BS was in EE, so I'm trying to catch up!).

I'm working on the following program to try to figure this out. Now, I'm at
the point where I'm filling up plines with (I belive) a list of pointers,
each of which is pointing to a string ("foo 1", "foo 2", and so forth). The
hard-coded 10 in the for loop, btw, is only for this exploration of ideas...
It will not be in the final code (indeed, none of the hard-code numbers will
be).

My two sticking points are:
1) I'm supposed to "free" stuff that I've malloc'd. If I do free(p),
then the pointers that I've stuffed into plines no longer point to anything,
and the printout loop at the end of main confirms that when free(p) is in
place.

2) I'm malloc'ing the correct size of each string, but how can I
dynamically grow plines as needed? The realloc man page tells me that I can
only realloc a thing that got it's address from a prior malloc... but where
can I malloc plines? It reeks of a chicken/egg situation at 12:30am.

Any insight or pointers [groan] are certainly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *plines[30];

int main(void){
char buf[1024];

int i;

for( i=0; i<10; i++ ){
char temp[1024];
sprintf(temp,"f oo %d",i);

char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines[i]=p;
}

for( i=0; i<10; i++ )
printf(">>> %s \n",plines[i]);

}

Nov 14 '05 #1
4 4072
In 'comp.lang.c', "John" <ia******@hotma il.com> wrote:
I'm trying (struggling) to use realloc to grow a list of strings. The
number of strings is not known (this is a subset of an assignment to
write a recursive ls program... my BS was in EE, so I'm trying to catch
up!).

I'm working on the following program to try to figure this out. Now,
I'm at the point where I'm filling up plines with (I belive) a list of
pointers, each of which is pointing to a string ("foo 1", "foo 2", and
so forth). The hard-coded 10 in the for loop, btw, is only for this
exploration of ideas... It will not be in the final code (indeed, none
of the hard-code numbers will be).
Ok. Starting with fixed size is a good approach. Better to process the points
one by one.
My two sticking points are:
1) I'm supposed to "free" stuff that I've malloc'd. If I do
free(p),
then the pointers that I've stuffed into plines no longer point to
anything, and the printout loop at the end of main confirms that when
free(p) is in place.
If you free before use, you cause an undefined behaviour. See my code below.
2) I'm malloc'ing the correct size of each string, but how can I
dynamically grow plines as needed?
Should be a flexible array of pointers to char. The type is char * * (aka
char **)

/* empty array */
{
char **pp = NULL;
}
The realloc man page tells me that I
can only realloc a thing that got it's address from a prior malloc...
but where can I malloc plines? It reeks of a chicken/egg situation at
12:30am.
It also said that realloc() with NULL acts like malloc().

/* grow to 3 pointers : (FAQ) */
{
char **pp = NULL;
...
{
void *p_tmp = realloc (pp, 3 * sizeof *pp);
if (p_tmp != NULL)
{
pp = p_tmp;
}
}
}

Note : the 3 pointers are not initialized.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *plines[30];

int main(void){
char buf[1024];

int i;

for( i=0; i<10; i++ ){
char temp[1024];
sprintf(temp,"f oo %d",i);

char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines[i]=p;
}

for( i=0; i<10; i++ )
printf(">>> %s \n",plines[i]);

}


Not bad. Here is your code revisited. HTH. Feel free to ask for details.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

int main (void)
{
int i;

char *plines[30];

for (i = 0; i < 10; i++)
{
char temp[8]; /* try 4 */

int n = sprintf (temp, "foo %d", i);

/* design checker (works in most cases) */
assert (n < sizeof temp - 1);

{
char *p = malloc (strlen (temp) + 1);

if (p != NULL)
{
strcpy (p, temp);
}
plines[i] = p;
}
}

for (i = 0; i < 10; i++)
{
printf ("[%p] -> '%s'\n", (void *) plines[i], plines[i]);
}

/* free the allocated arrays of char */
for (i = 0; i < 10; i++)
{
free (plines[i]), plines[i] = NULL;
}

/* just a checker... */
for (i = 0; i < 10; i++)
{
printf ("[%p]\n", (void *) plines[i]);
}

/* -ed- C90 compatibility */
return 0;
}

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #2
"John" <ia******@hotma il.com> wrote in message news:<YY******* *************@c omcast.com>...
I'm trying (struggling) to use realloc to grow a list of strings. The
number of strings is not known (this is a subset of an assignment to write a
recursive ls program... my BS was in EE, so I'm trying to catch up!).

I'm working on the following program to try to figure this out. Now, I'm at
the point where I'm filling up plines with (I belive) a list of pointers,
each of which is pointing to a string ("foo 1", "foo 2", and so forth). The
hard-coded 10 in the for loop, btw, is only for this exploration of ideas...
It will not be in the final code (indeed, none of the hard-code numbers will
be).

My two sticking points are:
1) I'm supposed to "free" stuff that I've malloc'd. If I do free(p),
then the pointers that I've stuffed into plines no longer point to anything,
and the printout loop at the end of main confirms that when free(p) is in
place.
I wouldn't free(p), But I would free(plines[whatever]) instead.

2) I'm malloc'ing the correct size of each string, but how can I
dynamically grow plines as needed? The realloc man page tells me that I can
only realloc a thing that got it's address from a prior malloc... but where
can I malloc plines? It reeks of a chicken/egg situation at 12:30am.

char **plines = NULL;
int num_plines = 0;

int main(void){
char buf[1024];
int len;

while ( your_condition )
{
if(!plines)
plines = malloc (sizeof(char*) * ++num_plines );
else
plines = realloc( plines, sizeof(char*) * ++num_plines );

assert(plines);

sprintf(buf,"fo o%d",num_plines ); // It will start from foo1,if you want
// to start from zero, change it.
len = strlen(buf) + 1;
char *p = malloc(len);
memcpy(p,buf,le n);
plines[num_plines-1] = p;
}

....
....
....
} // main
Any insight or pointers [groan] are certainly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *plines[30];

int main(void){
char buf[1024];

int i;

for( i=0; i<10; i++ ){
char temp[1024];
sprintf(temp,"f oo %d",i);

char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines[i]=p;
}

for( i=0; i<10; i++ )
printf(">>> %s \n",plines[i]);

}

Nov 14 '05 #3


John wrote:
I'm trying (struggling) to use realloc to grow a list of strings. The
number of strings is not known (this is a subset of an assignment to write a
recursive ls program... my BS was in EE, so I'm trying to catch up!).

I'm working on the following program to try to figure this out. Now, I'm at
the point where I'm filling up plines with (I belive) a list of pointers,
each of which is pointing to a string ("foo 1", "foo 2", and so forth). The
hard-coded 10 in the for loop, btw, is only for this exploration of ideas...
It will not be in the final code (indeed, none of the hard-code numbers will
be).

My two sticking points are:
1) I'm supposed to "free" stuff that I've malloc'd. If I do free(p),
then the pointers that I've stuffed into plines no longer point to anything,
and the printout loop at the end of main confirms that when free(p) is in
place.

The simple solution would free the allocations when you are finished
with them. So, change the printf loop to:

for( i=0; i<10; i++ )
{
printf(">>> %s \n",plines[i]);
free(plines[i]);
}
2) I'm malloc'ing the correct size of each string, but how can I
dynamically grow plines as needed? The realloc man page tells me that I can
only realloc a thing that got it's address from a prior malloc... but where
can I malloc plines? It reeks of a chicken/egg situation at 12:30am.

Instead of using char *plines[30], which fixes the max number of
strings you can allocate to 30, use char **. You can make a struct
that has a char ** member that points to the array and have another
member that keeps the count of the number of elements(string s)
allocated. You can write functions that manipulate this struct;
functions such as AddString, PrintStr, FreeStr. See the example. char *plines[30];

int main(void){
char buf[1024];

int i;

for( i=0; i<10; i++ ){
char temp[1024];
sprintf(temp,"f oo %d",i);

char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines[i]=p;
}

for( i=0; i<10; i++ )
printf(">>> %s \n",plines[i]);


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct sarray
{
char **line;
unsigned count;
};

int AddString(struc t sarray *p, const char *s);
void FreeString(stru ct sarray *p);
void PrintString(str uct sarray *p);

int main(void)
{
char buf[1024];
struct sarray mytest = {NULL}; /* Empty array */
int i;

for( i=0; i<10; i++ )
{
sprintf(buf,"fo o %d",i);
AddString(&myte st, buf);
}
PrintString(&my test);
FreeString(&myt est);
return 0;
}

int AddString(struc t sarray *p, const char *s)
{
char **tmp;

if((tmp = realloc(p->line,
(p->count+1)*(size of *tmp))) == NULL)
return 0;
if(tmp)
{
p->line = tmp;
if((p->line[p->count] = malloc(strlen(s )+1)) == NULL)
return 0;
strcpy(p->line[p->count++],s);
}
return 1;
}

void FreeString(stru ct sarray *p)
{
unsigned i;

for(i = 0; i < p->count;i++)
free(p->line[i]);
free(p->line);
p->line = NULL;
p->count = 0;
return;
}

void PrintString(str uct sarray *p)
{
unsigned i;

for(i = 0;i < p->count;i++)
printf("%6u: %s\n",i+1,p->line[i]);
return;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
Ahh... All the responses to my op were extremely helpful, and I've got
something going now. I think that one of the main sticking points for me
was the idea data being stored in an unnamed chunk of memory (i.e., no
variable name). But i suppose that the name isn't really necessary, as long
as the memory is set aside for it and the data can be access.

"John" <ia******@hotma il.com> wrote in message
news:YY******** ************@co mcast.com...
I'm trying (struggling) to use realloc to grow a list of strings. The
number of strings is not known (this is a subset of an assignment to write
a recursive ls program... my BS was in EE, so I'm trying to catch up!).

I'm working on the following program to try to figure this out. Now, I'm
at the point where I'm filling up plines with (I belive) a list of
pointers, each of which is pointing to a string ("foo 1", "foo 2", and so
forth). The hard-coded 10 in the for loop, btw, is only for this
exploration of ideas... It will not be in the final code (indeed, none of
the hard-code numbers will be).

My two sticking points are:
1) I'm supposed to "free" stuff that I've malloc'd. If I do free(p),
then the pointers that I've stuffed into plines no longer point to
anything, and the printout loop at the end of main confirms that when
free(p) is in place.

2) I'm malloc'ing the correct size of each string, but how can I
dynamically grow plines as needed? The realloc man page tells me that I
can only realloc a thing that got it's address from a prior malloc... but
where can I malloc plines? It reeks of a chicken/egg situation at
12:30am.

Any insight or pointers [groan] are certainly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *plines[30];

int main(void){
char buf[1024];

int i;

for( i=0; i<10; i++ ){
char temp[1024];
sprintf(temp,"f oo %d",i);

char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines[i]=p;
}

for( i=0; i<10; i++ )
printf(">>> %s \n",plines[i]);

}

Nov 14 '05 #5

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

Similar topics

18
2486
by: Dan | last post by:
hello, I would to know if it is possible to delete an instance in an array, The following does not allow me to do a delete. I am trying to find and delete the duplicate in an array, thanks for ( j =0; j<MAX ; j++) { for ( i =0; i<MAX ; i++)
3
2890
by: Goh, Yong Kwang | last post by:
I'm trying to create a function that given a string, tokenize it and put into a dynamically-sized array of char* which is in turn also dynamically allocated based on the string token length. I call the function using this code fragement in my main function: --- char** arg_array; arg_count = create_arg_array(command, argument, arg_array); for(count = 0; count < arg_count; count++)
8
3692
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
7
2932
by: Marlene Stebbins | last post by:
The bigint struct defines a big integer and represents it as a string of characters: typedef struct bigint { int sign; int size; int initflag; char *number; } bigint;
7
3788
by: Mischa | last post by:
Hello, I am trying to use realloc multiple times to extend an array of doubles but unfortunatly it keeps failing. I think I am mixing up the size to which the old memory block needs to be extended. So if it's already 128 in size it needs to be realloc'd to (ORIGSIZE + NEWSIZE) right ? I have provided a small example below, maybe that will make my describtion somewhat clearer... Thank you for any suggestions..
5
2996
by: matt.wolinsky | last post by:
Hello C++ gurus, I am trying to learn about how to use C++ memory management, and I know that there is no "renew" command in C++. What I am hoping to do is slightly different though. I want to implement a dynamic "array" by using an array of pointers to objects,
7
3002
by: Jonathan Shan | last post by:
Hello all, I am trying to run a program which has dynamic array of type struct. The program works until the line which uses realloc function to allocate more memory. I have tried to reproduce this in a simpler code, but in the simpler code the program works fine. Is there any reason realloc would just hang without producing any error
28
3885
by: bwaichu | last post by:
Is it generally better to set-up a buffer (fixed sized array) and read and write to that buffer even if it is larger than what is being written to it? Or is it better to allocate memory and realloc it for the size of the what is being written each time? In other words, what is the decision factor between deciding to use a fixed size buffer or allocating memory space and reallocing the size? I don't think the code below is optimal...
28
7173
by: Trups | last post by:
HI, I want to dynamically allocate array variable of type LPWSTR. Code looks like this... main() { LPWSTR *wstr; int count = Foo (wstr); for (int i = 0; i < count; i++)
0
9652
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10523
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
10560
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
9345
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
6966
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
5636
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...
1
4434
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
3993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3088
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.