Dynamic array in C — Is my understanding of malloc and realloc correct?

前端 未结 3 1519
梦如初夏
梦如初夏 2020-12-12 17:25

I am learning how to create dynamic 1D arrays in C. The code below tries to do the following:

  1. Using malloc, create a dynamic array of length
3条回答
  •  渐次进展
    2020-12-12 17:57

    You're close.

    In C (at least since the 1989 version of the standard), the cast before malloc and realloc is unnecessary, since C can convert values of type void * to int * 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 malloc call:

    double *data = malloc(10 * sizeof *data);
    

    Since the type of the expression *data is double, sizeof *data is equivalent to sizeof (double). This also means you don't have to adjust your malloc calls if the type of data changes.

    As for the realloc call, it's safer to assign the result to a temporary pointer value. realloc will return NULL if it cannot extend the buffer, so it's safer to write

    double *tmp;
    ...
    tmp = realloc(data, 11 * sizeof *data);
    if (!tmp)
    {
      // could not resize data; handle as appropriate
    }
    else
    {
      data = tmp;
      // process extended buffer
    }
    

    Be 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.

提交回复
热议问题