Question:
C/C++ programming question - malloc () parameters?
racux
2012-03-09 17:17:31 UTC
I am writing this in C but I believe it also works for C++. Basically I have a float array and want to set the size of the array equal to an integer:

float *n;
int value;

n = (float *)malloc(value * sizeof(float));

Can someone confirm that I am doing this right? That one of the 'float's in the definition does not be redefined to an 'int'?
Four answers:
anonymous
2012-03-09 17:52:21 UTC
The cast isn't necessary in C. The void * will be cast to the correct representation for float * without it. Also, if value is storing the number of floats you want to allocate, it's easier just to do "n = malloc(value * sizeof *n);". That way you only have to change the definition of n, if you end up changing its type.



Anyway, the code you've written is fine. Be sure to check that n isn't a null pointer after the call, since malloc returns a null pointer if something went wrong.
Michael
2012-03-09 17:47:52 UTC
Yes, that works although it is poor style in both C and C++ (but for different reasons).



In both cases you should first #include in order to get the correct function prototype for malloc() in scope.



In the C case it would be better to write:



float *n = malloc(value * sizeof(*f));



Note that there is no need to cast the return value of malloc() in C (and it is often regarded as poor style to do so because it can hide the lack of a correct function prototype for malloc())



Also consider using the form sizeof(*f) and thus avoiding the need to know the type of object that f points to.



In C++ it *is* necessary to cast the return value of malloc(), but using malloc() at all would normally be regarded as poor C++ style since the preferred idiom in C++ would be:



n = new float[size];
oops
2012-03-09 17:22:42 UTC
Assuming you actually set the value of the variable 'value' somewhere to a non-negative number. Also assuming that when you say 'size of the array', you actually mean 'number of elements in the array' and not 'size of the array in bytes'. Yes, you are doing it correctly.
mally
2016-11-18 14:28:24 UTC
very own abode page 5 is unquestionably very own abode page plus merchandise orientation , so very own abode page 5 is extra appropriate than like very own abode page 3 in this feeling , as merchandise oriented programming encourages re usability of code and diverse sturdy stuff


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...