如何在c中创建动态大小的数组?

时间:2014-04-23 09:20:05

标签: c arrays dynamic

如何创建动态数组? 我尝试使用该代码:

#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;
}

我怎么能意识到这一点?我的程序(Visual Studio 2013)会出错。

1 个答案:

答案 0 :(得分: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;
}