Re: String array
- From: "pinkfog" <chjiangwh@xxxxxxxxx>
- Date: 12 Apr 2006 03:52:30 -0700
stathis gotsis wrote:
<alex323@xxxxxxxxx> wrote in messageI have a question:
news:1144768490.269465.313720@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hey everybody. I am coding a function that takes a string as an
argument (char *msg) and breaks it up into pieces. The result will be
stored in (char ***fragments) which is passed as an argument. The
caller calls myfunction(mymsg, &my_fragment_array) where
`my_fragment_array' is a char **. My problem is that the array is
perfectly constructed inside the function, but when I switch frames in
GDB to see the caller, the second element of the array is either null
or memory garbage. How can I dynamically allocate an array of strings
from inside a function for use outside a function?
You could do something like this:
#include <stdlib.h>
#define STRING_NUMBER 10
#define STRING_LENGTH 20
char **foo(void)
{
int i;
char **temp=malloc(STRING_NUMBER *sizeof *temp);
if (temp==NULL)
/*Do something*/;
for (i=0;i<STRING_NUMBER;i++)
{
temp[i]=malloc(STRING_LENGTH);
if (temp[i]==NULL)
/*Do something*/;
}
return temp;
}
,adjusting it to your needs for variable number of strings, variable string
length and so on. In the former case you will need a mechanism to pass that
variable number of strings back to the caller. Do not forget to free all
allocated memory back in your main() program.
in the for-statement,you use malloc for STRING_NUMBER times,does it
mean that you must use free for STRING_NUMBER times or not?I am
confused.Hope you can help.thx.
.
- Follow-Ups:
- Re: String array
- From: stathis gotsis
- Re: String array
- References:
- String array
- From: alex323
- Re: String array
- From: stathis gotsis
- String array
- Prev by Date: Re: life cycle
- Next by Date: Re: a[++j]=a[j]+a[j+1];
- Previous by thread: Re: String array
- Next by thread: Re: String array
- Index(es):
Relevant Pages
|
|