-3

How can i create a dynamic array? I tried with that code:

#include <stdlib.h>
#include <stdio.h>
int main()
{
int size=0,*value,array[size];
printf("How many array elements do you need?");
scanf_s("%i",&size);
value = (int *)malloc(size*sizeof(int));
printf("Your array has now %i elements.Here are the contents:",size);
for(i=0;i<size;i++)
{
  printf("%i",array[i]);
}
return 0;
}

How can i realize that? My program(Visual Studio 2013) gives errors.

  • Indent your code and add the required ';'s at the end of most statements. – Jabberwocky Apr 23 '14 at 09:22
  • 1
    The array array is initialized as an array with size 0. Note that the dynamic one is pointed by the pointer value. You can use the pointer in the same way as an array to see the values of the dynamic array, just chance in the printf array[i] to value[i] – Luis Alves Apr 23 '14 at 09:24
  • Read about `arrays in C` and about `using malloc`. – tod Apr 23 '14 at 09:26
  • 1
    And finally, [don't cast the return value of standard allocator functions](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). – The Paramagnetic Croissant Apr 23 '14 at 09:27
  • Also since You are using malloc which allocates dynamic memory, it's good practice to release this memory after You use it, just out on the end. of your program free(value). (Note that the operative system also does this in the end of the execution, but it's a good practice to do it) – Luis Alves Apr 23 '14 at 09:29
  • Apparently the Visual Studio 2013 compiler doesn't support [VLAs](http://en.wikipedia.org/wiki/Variable-length_array). – Jabberwocky Apr 23 '14 at 09:30
  • 2
    By the way, the values You will see, will be totally random, because C doesn't put all the array values in 0 – Luis Alves Apr 23 '14 at 09:30
  • ok, thx. Can pls someone correct my code? I need an example for learing. thx ;) – user3563783 Apr 23 '14 at 09:35
  • @LuisAlves you mean printf("%i",value[i]);? – user3563783 Apr 23 '14 at 09:38
  • yes it's printf("%i",value[i]); – Luis Alves Apr 23 '14 at 10:14

1 Answers1

0
#include <stdlib.h>
#include <stdio.h>

int main(){
   int i, size, *value;
    printf("How many array elements do you need?");
    scanf_s("%i", &size);
    value = (int *)malloc(size*sizeof(int));
    printf("Your array has now %i elements.Here are the contents:\n", size);
    for(i=0;i<size;i++){
        printf("%i\n", value[i]);//uninitialize
    }
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70