Malloc or normal array definition?

前端 未结 4 1345
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 13:56

When shall i use malloc instead of normal array definition in C?

I can\'t understand the difference between:

int a[3]={1,2,3}
int array[sizeof(a)/siz         


        
4条回答
  •  余生分开走
    2020-12-06 14:29

    You definately have to use malloc() if you don't want your array to have a fixed size. Depending on what you are trying to do, you might not know in advance how much memory you are going to need for a given task or you might need to dynamically resize your array at runtime, for example you might enlarge it if there is more data coming in. The latter can be done using realloc() without data loss.

    Instead of initializing an array as in your original post you should just initialize a pointer to integer like.

    int* array; // this variable will just contain the addresse of an integer sized block in memory
    int length = 5; // how long do you want your array to be;
    
    array = malloc(sizeof(int) * length); // this allocates the memory needed for your array and sets the pointer created above to first block of that region;
    
    int newLength = 10;
    array = realloc(array, sizeof(int) * newLength); // increase the size of the array while leaving its contents intact;
    

提交回复
热议问题