« first day (2026 days earlier)      last day (1590 days later) » 

6:06 AM
 #include <stddef.h>
// return a *new, dynamically allocated* array with each element doubled.
int *maps(const int *arr, size_t size)
{
  int a[size];
  for(int i = 0;i<size;i++)
  {
    a[i] = 2*arr[i];
  }
  return *a;
}
I have to take an array and return a different array with every entry doubled. like [1,2] -> [2,4]
What i have done wrong in my code?
 
 
5 hours later…
11:23 AM
My dude. What have you done
@AjayMishra When function maps is called, it created int a[size] on the stack. Then did what you wanted. You take the address of this array on the stack, and then return it to the caller. The stack is then destroyed because the function finished. And you are left with a pointer that means nothing anymore.
In short: The array created in the function will only exist while the function is running. When it stops, the array is destroyed. So you cannot do this if you want to keep the array.
 
 
2 hours later…
1:47 PM
@AjayMishra So, as Micrified said, it's not actual a dynamically allocated array. It's VLA (Variable Length Array), which is allocated statically and only the lenght is determined during runtime.
 
How can I do a dynamic array allocation? as new is not available in C.
 
@AjayMishra to allocate some dynamic memory You should use malloc()/free().
 
Okay, thanks.
 

« first day (2026 days earlier)      last day (1590 days later) »