Please post clean standard C code which compiles:
$ gcc -ansi -pedantic -Wall -O malloc.c
malloc.c:2: warning: return type defaults to `int'
malloc.c: In function `main':
malloc.c:4: warning: implicit declaration of function `initialize_f'
malloc.c:6: error: parse error before '/' token
malloc.c: At top level:
malloc.c:12: error: conflicting types for 'initialize_f'
malloc.c:4: error: previous implicit declaration of 'initialize_f' was here
malloc.c: In function `initialize_f':
malloc.c:14: warning: implicit declaration of function `malloc'
malloc.c:16: error: parse error before '...' token
It does not cost more than three extra lines to improve it.
Apart from the // comments being not part of C89 (which I inferred
from your use of main()), they also are considered dangerous in
usenet as they are not stable through a linebreak.
sp******@yahoo.com wrote:
main()
#include <stdlib.h>
void initialize_f (float *f);
int main (void) {
float * f;
initialize_f(f);
// ...use f for processing
/* use f for processing */
free(f);
return 0; }
void initialize_f(float * f)
{
long n = 100;
f = (float*)malloc(n*sizeof(float));
f = malloc(n * sizeof *f);
is better C, does not mask the error of forgetting to
#include <stdlib.h> and is stable through a type change
of f.
f[1] = ... // etc. fill f array here
You forgot a comment about safety checks on the return value
of malloc() or the actual checks.
f[0] = 0.0F;
/* etc fill f array here */ }
The size of the array is only known once initialize_f() is called so I
can't allocate it in main(). Please can someone tell me if f will be
initialized correctly by this code? Thanks :)
No.
If you want some object O of type T modified by a function,
you do not pass O but the address of O (i.e. a T* argument).
Otherwise, you only have a copy of O for which all steps
you deem necessary are performed -- but this copy of O dies
after the function is left and the original O is unchanged.
So, you want to pass &f to initialize_f, which consequently
has a float** parameter.
Finally, if you really work with array-like semantics for f,
it is better to pass the size info out of initialize_f(),
e.g. as a return value.
#include <stdlib.h>
size_t initialize_f (float **fptr);
int main (void)
{
float *f;
size_t fsize;
if (0 == (fsize = initialize_f(&f))) {
/* error handling */
}
/* use f */
free(f);
return 0;
}
size_t initialize_f (float **fptr)
{
size_t i, n = 100;
*fptr = malloc(n * sizeof **fptr);
if (NULL == *fptr) {
/* maybe error handling; cheap alternative: */
return 0;
}
for (i=0; i<n; i++)
(*fptr)[i] = (float)i/n;
return n;
}
Note: float is almost never the right type for floating
point values -- you run relatively early into precision
and rounding error issues at (most of the time) no gain.
Use double by default and float where you need it.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.