A
Adam
Hi,
I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.
After much perusing of the internet I found a related answer here (by
Eric Sosman) which involved creating an array of pointers and using
that, so it looks something like:
void foo(char *sptr[], int items)
{
char buff[50];
while (--items >= 0)
{
sprintf (buff, "foo%d", items);
sptr[items] = malloc(strlen(buff) + 1);
if (sptr[items] == NULL)
exit(0);
strcpy (sptr[items], buff);
}
}
int main(void)
{
int total = 10;
char *p[total];
foo(p, total);
printf(p[1]);
return 0;
}
This works a treat (I can access my strings, e.g. the printf line) but
how would I do a similar thing if I don't know how long my list is going
to be? E.g. "total" only gets found out inside foo.
Thanks a lot,
Adam
I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.
After much perusing of the internet I found a related answer here (by
Eric Sosman) which involved creating an array of pointers and using
that, so it looks something like:
void foo(char *sptr[], int items)
{
char buff[50];
while (--items >= 0)
{
sprintf (buff, "foo%d", items);
sptr[items] = malloc(strlen(buff) + 1);
if (sptr[items] == NULL)
exit(0);
strcpy (sptr[items], buff);
}
}
int main(void)
{
int total = 10;
char *p[total];
foo(p, total);
printf(p[1]);
return 0;
}
This works a treat (I can access my strings, e.g. the printf line) but
how would I do a similar thing if I don't know how long my list is going
to be? E.g. "total" only gets found out inside foo.
Thanks a lot,
Adam