-2

This is also a valid code to declare dynamic arrays.

malloc needs pointers, this doesn't. Is this a better method?

 printf("enter the size of array")
 scanf("%d",&x)
 const int size
 size = x
 int array[size]
Venson
  • 1,772
  • 17
  • 37
Rafed Nole
  • 112
  • 1
  • 4
  • 16
  • As far I know, VLA are exactly as `malloc()` at run-time. Also, why do you think that pointers are bad? note that you're using VLA, that's a valid code according to C99 standard only. – The Mask Aug 05 '13 at 15:52
  • That code won't compile, even if you add the missing semicolons. – Tom Tanner Aug 05 '13 at 15:57
  • As @TomTanner said this won't compile, so no this isn't a better method. – Scotty Bauer Aug 05 '13 at 16:03
  • the code is working properly. array can be created and used like that. – Rafed Nole Aug 05 '13 at 16:29
  • Example code that compiles without modification usually get a better reception on SO, i.e. having to add `;` and fixing reassignment to `const` variables which is not legal etc... ideally it should be a [SSCCE](http://www.sscce.org/). – Shafik Yaghmour Aug 05 '13 at 16:30
  • @user2653718 No it cannot. `int main(){ const int test; test =1;}` When compiled: `t.c:7: error: assignment of read-only variable "test"` – Scotty Bauer Aug 05 '13 at 16:32
  • There are several online compilers available from this thread: http://stackoverflow.com/questions/3916000/online-c-compiler-and-evaluator if you don't have one currently available and as far as I know they all support C as well as C++. – Shafik Yaghmour Aug 05 '13 at 16:38
  • #include #include int main() { int x,i; scanf("%d",&x); const int n=x; int array[n]; for( i=0;i – Rafed Nole Aug 05 '13 at 16:44
  • @user2653718 Posting code edits in the comment is not readable, you can just edit your question and replace the existing code. – Shafik Yaghmour Aug 05 '13 at 16:47
  • in some compilers it works but on some it says segmentation fault or runtime error. – Rafed Nole Aug 05 '13 at 16:47

1 Answers1

1

It is hard to say if one is better than the other, a better question would be what are the advantages of each, you need to decided based on your requirements but using malloc and using variable length arrays(VLA) are not the same.

There are some major differences.1) A VLA will usually be allocated on the stack although that is an implementation decision, the standard just says there are automatic. The stack is more limited than the the heap which is where a malloc'ed array will go and so you can easily overflow your stack. 2) You need to free a malloc'ed array a VLA is an automatic variable and will not exist outside of the scope it is declared in. 3) VLA is part of the C99 standard and so code using VLA will not be portable.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740