On 21 Mar 2007 12:45:39 -0700, "william" <wi**********@gmail.com>
wrote:
>My situation is here:
an array of two dimension can only be defined locally within a
function(because the caller don't know the exact size ). Then the
question is: how should the caller access this array for future use?
The code is:
**********************
caller()
{
...
function();
other code also wish to access the array elements in function, how
should I do?
}
function()
{
calculation I want to encapsulate within this function.........
...
got the size: 'num_of_row' and 'num_of_col'
char maze[num_of_row][num_of_col];
...
code to fill the array
return;
}
I consider to use malloc() to allocate memory for this array, and
return the pointer to this run time allocated memory back to the
caller, however, another question arise: can the caller possibly
access this local memory(got from malloc())? because I think it's
still only belong to the function being called----rules of scope
suppose to work.
Can any one explain the memory allocation when compiling (in stack)
and at run time (heap)?
And what kind of rules are on top of these two different kinds of
resources? Which should C programmer should pay attention to?
I am kind of lost into these concepts when I debug my program:-)
Allocated memory remains allocated until it is explicitly freed. In
order for the calling function to know the address of the allocated
memory, the called function must make it available. There are several
techniques to make it available. Two popular ones are: it can be
returned with a return statement and it can be stored in a variable
the calling function has access to (such as a global variable).
In addition to the address of the allocated memory, the calling
function also needs to know the number of dimensions (always two in
your example) and the size of each.
Now that we know the called function must make three values available
to the calling function, return seems like a poor choice. However, if
the calling function passes some object addresses to the called
function, the called function can store the appropriate values in
those objects. Consider the following stripped down code just to
illustrate the technique.
int called_function(char **ptr_to_ptr, size_t *dim1, size_t *dim2){
*ptr_to_ptr = malloc(total_size_of_array);
*dim1 = size_of_first_dimension;
*dim2 = size_of_second_dimension;
return some_status_value;
}
int main(void){ /* calling function */
char *array;
size_t first_dimension;
size_t second_dimension;
inst status;
status = called_function(&array, &first_dimension,
&second_dimension);
/* If status indicates success, use the array. To access element
[i][j] use the expression array[i*first_dimension+second_dimension].
*/
Remove del for email