-1

As far as I know C doesn't support dynamic arrays. Here I implemented a dynamic array tasks with a variable length TASK_NO which I am fetching through scanf. The code is compiled without error and it is running properly. What can be the reason? Please clarify.

scanf("%d" , &TASK_NO);
int counter=TASK_NO;
struct task_info tasks[TASK_NO];
printf("total: %d\n", sizeof(tasks)/sizeof(tasks[0]));

`

Shiladitya Bose
  • 893
  • 2
  • 13
  • 31
  • 1
    This is called a VLA (variable length array), and is supported since C99 (although not required in C11) – user4520 Nov 18 '15 at 16:38
  • The `sizeof()` keyword is evaluated at compile time, not runtime, so will not give the correct number for `total` – user3629249 Nov 18 '15 at 16:41
  • What is the reason for down vote? Is the question quality so poor or the answer is so well known ? – Shiladitya Bose Nov 18 '15 at 16:52
  • Not my down-vote but I expect it's because of any/all of the following: (a) no prior research effort shown, (b) answer is readily available via a simple Google search, (c) numerous duplicates on StackOverflow already. – Paul R Nov 18 '15 at 17:04
  • 1
    @ user3629249, since C99 there are runtime requiremens for sizeof. – Paul Ogilvie Nov 18 '15 at 17:29

1 Answers1

4

struct task_info tasks[TASK_NO]; is not a dynamic array. It is a variable length array whose length will be decided on run time.


Dynamic arrays would be arrays whose size can be changed as and when required. Think of an array which you initialized to contain 10 elements and later would want to change it to contain 20 elements. That is not present in C.


You can however implement dynamic arrays yourself using pointers, dynamic memory allocation and realloc(). But that won't be something that is a feature provided by the language.

Haris
  • 12,120
  • 6
  • 43
  • 70
  • Well, it can if you implement it yourself using dynamic memory allocation. – user4520 Nov 18 '15 at 16:38
  • Yes, that can be done in C, but not as a syntactic feature. It can be done by declaring a pointer, allocating space to that pointer and treating the pointer as an array. You change the array size with `realloc`. – Paul Ogilvie Nov 18 '15 at 16:38
  • 2
    @szczurcio True. I think Stroustrup started that around 1979. It kinda got out of hand though. – Peter - Reinstate Monica Nov 18 '15 at 16:40
  • There is no reason to say that is not possible, just because we don't know if there is a way or not. We do have pointers and malloc. Should be enough. – Michi Nov 18 '15 at 16:53
  • @Michi, I changed the answer a little. Do take a look. – Haris Nov 18 '15 at 16:55
  • @Haris I saw that now :). But like I said, we have [pointers and malloc](http://stackoverflow.com/questions/33655093/array-with-undefined-length-in-c/33656480#33656480) – Michi Nov 18 '15 at 16:57
  • @Michi, Ya.. I added your suggestion also. :) – Haris Nov 18 '15 at 16:59
  • @Haris ....and you got my vote for that :d. – Michi Nov 18 '15 at 17:02