can size of array be determined at run time in c?

前端 未结 6 1987
日久生厌
日久生厌 2020-11-29 08:24

As I know, an array needs to have a specific size before compiling time in c.

I wonder why this code still works?

int s;
printf(\"enter the array si         


        
6条回答
  •  Happy的楠姐
    2020-11-29 08:57

    You are confusing two things here.

    1) Determining the size of an already allocated array (which your title implies): divide sizeof() for the total by the size of one (say, the first) element:

     sizeof(a)/sizeof(a[0])
    

    2) Dynamically allocating memory as your question asks:

     int *a = (int*)malloc( s * sizeof(int) );
    

提交回复
热议问题