0

As known, there are two types of arrays, static and dynamic. Static arrays size is defined at compile time, dynamic array size is defined using malloc. In this code you can see that I haven't use malloc and I am dealing with dynamic array and my all array`s operations are running.

int main()
{
    int capofarr,sizeofarr,i,choice,choice2,ele,pos,choice3;
    printf("enter the size of array:");
    scanf("%d",&capofarr);
    int arr[capofarr];
    printf("Enter the element that you want to store in array:");
    scanf("%d",&sizeofarr);
    if(capofarr>=sizeofarr)
    {
    
    for(i=0;i<=sizeofarr-1;i++)
    {
    printf("Enter value of arr[%d]=",i+1);
    scanf("%d",&arr[i]);
    }
Rohan jangid
  • 125
  • 3
  • 13
  • 4
    What you have defined is a variable-length array (VLA). If your question is "why is malloc still needed if VLAs exist?", one good reason is that malloc provides memory from the heap, which means it can be passed around to other functions, something that a local variable cannot do. – Outrageous Bacon Oct 09 '20 at 04:57
  • VLAs are not intended as a replacement for dynamically-allocated memory (`malloc`/`calloc`/`realloc`). They are a recent addition to the language that's been made optional, and are not present in all implementations. They aren't as useful as dynamic memory - VLAs cannot be resized after being defined, they cannot be members of `struct` or `union` types, they cannot be defined at file scope, and in most implementations they are quite limited in size. It's like comparing a chisel to a screwdriver - both are useful, but have very different uses. – John Bode Oct 09 '20 at 18:51

1 Answers1

0

Yes your all operations are running, but the purpose of malloc is to allocate the quantity of memory that is required so that memory doesn't get wasted. But in your case i condition of (capofarr > sizeofarr) the memory is being wasted ie. the size of wasted memory will be (capofarr-sizeofarr)*sizeof(a[0]). Please correct me if i am wrong. Thanks

saty035
  • 142
  • 2
  • 7
  • if user enter the size of array 5 and want to use only 2 instead of all 5 then the 3 remaning is waste memory? – Rohan jangid Oct 09 '20 at 07:40
  • He can always decide to use it later on, I don't see how it is a "waste" of memory. You can choose to allocate space for 5 ints and use only 3 with dynamic memory too. – Silidrone Oct 09 '20 at 09:23
  • @Silidrone yaa understood thnx – Rohan jangid Oct 12 '20 at 02:33
  • @Rohanjangid the unused indices in array will store garbage value which in case of large programs increases time complexity and slows down the compilation. thnx. – saty035 Oct 13 '20 at 04:08