Brett said:
Sorry for the rookie question....
If I have a pointer array (for example):
char *colors[] = {
"blue",
"green"
};
and I want to add yellow to this array later in my code....how would I do
that?
I'm curious. Why would you want to add it later?
I would include it in the original declaration.
If you wish, you can dynamic allocate the array. This would
be costly in efficiency because you are doing this just to
control one small area of memory "yellow".
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct COLORS
{
const char **color;
size_t cnt;
} COLORS;
int AddColor(COLORS *p,const char *s);
void FreeColors(COLORS *p);
int main(void)
{
size_t i;
COLORS my = {NULL};
AddColor(&my,"blue");
AddColor(&my,"green");
puts("\tColors in array");
for(i = 0; i < my.cnt;i++)
printf("%u. %s\n",i+1,my.color
);
/* now add a color */
AddColor(&my,"yellow");
puts("\n Attempt to add the color yellow\n");
puts("\tColors in array");
for(i = 0; i < my.cnt;i++)
printf("%u. %s\n",i+1,my.color);
FreeColors(&my);
return 0;
}
int AddColor(COLORS *p,const char *s)
{
char **tmp;
if((tmp = realloc((char **)p->color,
(p->cnt+1)*(sizeof *tmp))) == NULL)
return 0;
p->color = tmp;
if((p->color[p->cnt] = malloc(strlen(s)+1)) == NULL)
return 0;
strcpy((char *)p->color[p->cnt++],s);
return 1;
}
void FreeColors(COLORS *p)
{
size_t i;
for(i = 0; i < p->cnt; i++) free((char *)p->color);
free((char **)p->color);
p->color = NULL;
p->cnt = 0;
return;
}
--
Al Bowers
Tampa, Fl USA
mailto: (e-mail address removed) (remove the x to send email)
http://www.geocities.com/abowers822/