Variable Sized Arrays vs calloc in C

前端 未结 5 1982
挽巷
挽巷 2020-12-03 06:37

On the discussion of dynamic memory here: \"Intro to C Pointers and Dynamic Memory\"

The author states:

A memory block like this can effective

5条回答
  •  生来不讨喜
    2020-12-03 07:09

    Because

    int array[variable];
    

    isn't valid in standard C -- you can only define the length of an array with a constant. (such as your

    char name[] = "Nick";
    

    example, which isn't variable-length).

    As such, it's necessary to use a memory allocator like calloc() if you want to create an array of a length based on a program variable.

    Just don't forget to free() it.

提交回复
热议问题