Re: Returning an array of strings in C
- From: SM Ryan <wyrmwif@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 12 Nov 2005 07:58:24 -0000
karthika.28@xxxxxxxxx wrote:
# Hi,
#
# I am writing a function that needs to return an array of strings and I
# am having some trouble getting it right. Can you help me answer the
# following questions?
#
# 1. How does the function return the array?
It doesn't. It returns a pointer. You have to ensure the memory
is available to the caller after the return; usually that means
static or mallocked from the heap. If you return mallocked
memory, the caller has to free to reclaim the heap.
# 2. How should the function be declared?
char *dupstr(char *string) {
return strcpy(malloc(strlen(string)+1),string);
}
# 3. How is the return value captured by the calling program?
You can assign it to appropriate pointer variable.
char *duplicate = dupstr("aleph beth gimel");
# Here is what I consider an array of 100 strings:
# char *array_string[100]
You might have to do something like
char **function(void) {
char **result = malloc(100*sizeof(char*));
int i;
for (i=0; i<100; i++) {
result[i] = malloc(n(i));
}
return result;
}
...
char **A = function(); int i;
....
for (i=0; i<100; i++) free(A[i]); free(A);
...
--
SM Ryan http://www.rawbw.com/~wyrmwif/
Death is the worry of the living. The dead, like myself,
only worry about decay and necrophiliacs.
.
- References:
- Returning an array of strings in C
- From: karthika . 28
- Returning an array of strings in C
- Prev by Date: Re: [OT] commands vs functions (was: Re: Find Mac Address)
- Next by Date: Re: About (char)13 & (char)10
- Previous by thread: Returning an array of strings in C
- Next by thread: Re: Returning an array of strings in C
- Index(es):
Relevant Pages
|