Variable Sized Arrays vs calloc in C

前端 未结 5 1958
挽巷
挽巷 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 06:51

    If you declare int array[variable] the memory will be allocated on the stack which is not very good for large, relatively permanent data structures (such as one you might want to return). You don't need to free memory manually if you use the array syntax since it's freed when it goes out of scope. calloc on the other hand will allocate memory dynamically at run time on the heap. You'll have to free it yourself as soon as you're finished with it.

    0 讨论(0)
  • 2020-12-03 06:53

    Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. So, don't foget to set compiler flag -std=c99 or -std=gnu99. Following example will work

    #include<stdio.h>
    
    int main()
    {
        int n;
        printf("\n\tEnter the number of digits: ");
        scanf("%d", &n);
    
        char str[n];
        for(int i=0; i < n; i++) {
            scanf("%s", &str[i]);
        }
    
        printf("\n\tThe entered digits are: %s", str);
    return 0;
    }
    

    I garantee that :-)

    0 讨论(0)
  • 2020-12-03 07:00

    Using variable sized arrays on the stack as an auto variable (instead of the heap using calloc/malloc/new/etc) is not a bad idea for a process that is going to run for a long time and will need to make and destroy lots of little arrays. This is because the stack is guaranteed not to ever become fragmented, while memory can and will get fragmented. If you are writing firmware or a service that needs to run for years without stopping, you are almost prohibited from using malloc or new.

    0 讨论(0)
  • 2020-12-03 07:05

    I agree with ocdecio that c89 doesn't allow

    int array[variable]
    

    c99 allows some types of variables and expressions to be the array size. But in addition to that, things allocated with malloc and family can be resized using realloc.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题