Re: a question of style



questions? wrote:


Artie Gold wrote:
questions? wrote:
I am curious about whether I should do this

say I want to calculate dot product of two matrix(4X4,fixed)
I do two ways

1)
void dot_product(double A[4][4] , double B[4][4], double
result[4][4]){ blah blah

}

my results are automatically given back in the matrix result[4][4]

or

2)
double [4][4] dot_product(double A[4][4],double B[4][4]){
double result[4][4];
blah blah

return result;
}

for the second type, result is local variable and will be released
after function call, Will the program have problem to access?

Are there better and neat way to this problem?

Thanks

Well since option 2 is not an option at all (arrays are not a first
class type in C, so an array cannot be a return value), you're left
with option 1.

The other option would be to wrap your array in a struct and return
that, but that would depend upon how you plan on using this code...

BTW - explicitly mentioning the first dimension of a passed array is
superfluous; i.e. `double A[][4]' and `double A[4][4]' -- or for
that matter double A[400][4] -- mean the same thing.

I see, I see.
but Do you have the same problem?

Say you locally define a structure which has the array you want to
return.
when you return that, you are pointing to a local variable which will
be released?

Only if you returned a pointer. With the struct variant, you return the
struct, so a copy is made of it. There's no pointer to a local variable
the way there can be with an array.


Brian
.



Relevant Pages

  • Re: Passing an array of structuresfrom a pointer?
    ... an array of struct. ... You cannot assign a pointer to struct to a long* ... to only declare structs in headers and then define the ...
    (microsoft.public.vc.language)
  • Re: Looking for a more elegant way to do memory offsets
    ... The mallocfunction returns memory that is "suitably aligned" ... >which in it contains the pointer to the first element in the linked ... and here a "struct dem_mem" does not contain a pointer to another ... This is not a linked-list access, but rather an array access: ...
    (comp.lang.c)
  • Re: Passing an array of structuresfrom a pointer?
    ... to only declare structs in headers and then define the ... the struct should be declared ... what if you have a simple array like this: ... It also returned the value of the pointer. ...
    (microsoft.public.vc.language)
  • Re: I went a help
    ... int main{ ... nig is an array of struct. ... Since name is a pointer, ...
    (comp.lang.c)
  • Re: Pointer to array of structs?
    ... I have made a struct. ... Now I would like to make a pointer an array with 4 ... int main ...
    (comp.lang.c)