I am learning how to create dynamic 1D arrays in C. The code below tries to do the following:
- Using
malloc, create a dynamic array of length10, that holds values of typedouble. - Set each entry of the array to
j/100forj = 0, 1,..., 9. Then print it out. - Add an additional empty entry to the end of the array using
realloc. - Set the new entry to
j/100and print out each entry again.
Testing:
double* data = (double*)malloc(10*sizeof(double));
for (j=0;j<10;j++)
{
data[j]= ((double)j)/100;
printf("%g, ",data[j]);
}
printf("\n");
data = (double*)realloc(data,11*sizeof(double));
for (j=0;j<11;j++)
{
if (j == 10){ data[j]= ((double)j)/100; }
printf("%g, ",data[j]);
}
free((void*) data);
Questions
-
Am I coding this right?
-
Tutorials I found use
mallocwithout putting the(double*)in front. E.g.,int *pointer;
pointer = malloc(2*sizeof(int));
This does not compile for me on Visual Studio 2010, Windows 7. The error message is
value of type void cannot be assigned to entity of type
int.
Why does it work for those tutorials and not for me? Am I right to guess that it is because the compilers they are using automatically fill in the (int*) for them in my example?
You’re close.
In C (at least since the 1989 version of the standard), the cast before
mallocandreallocis unnecessary, since C can convert values of typevoid *toint *without a cast. This is not true for C++, so based on the error you’re getting, it sounds like you’re compiling this code as C++ and not C. Check the documentation for VS2010 to determine how to compile code as C.The following is my preferred style for writing a
malloccall:Since the type of the expression
*dataisdouble,sizeof *datais equivalent tosizeof (double). This also means you don’t have to adjust yourmalloccalls if the type ofdatachanges.As for the
realloccall, it’s safer to assign the result to a temporary pointer value.reallocwill return NULL if it cannot extend the buffer, so it’s safer to writeBe aware that Microsoft’s support for C ends with the 1989 version of the language; there have been two revisions of the language standard since then, which have introduced some new features and deprecated old ones. So while some C compilers support C99 features like mixed declarations and code, variable length arrays, etc., VS2010 will not.