J
John
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,"foo %d",i);
char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines=p;
}
for( i=0; i<10; i++ )
printf(">>> %s \n",plines);
}
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,"foo %d",i);
char *p = malloc( strlen(temp) + 1 );
strcpy(p,temp);
plines=p;
}
for( i=0; i<10; i++ )
printf(">>> %s \n",plines);
}