0

this code is correct in C#

int x = int.Parse(Console.ReadLine());
        int[] t = new int[x];

but in c/c++ in wrong

int n;  scanf("%d",&n);  int a[n];

how in c# static array allocate in runtime (or in c# array is dynamic?)

3
  • 9
    You should accept answers to your questions. Commented Nov 19, 2010 at 17:05
  • 1
    Here's how SO works. You ask questions, we answer them to the best of our ability. When you receive an answer that you like, upvote it by clicking the up arrow ^ next to that answer. One of the answers provided will be the best answer for your particular situation. You should "Accept" than answer by clicking the check mark next to that answer. When you upvote or accept answers, the answerer received "reputation points" for their effort, which is the currency that drives the site. You've asked many questions, but never accepted any answers. Please go back and accept the answers Commented Nov 19, 2010 at 17:43
  • I'm not sure I understand what you are trying to ask here. Can you clarify? Commented Nov 19, 2010 at 17:52

3 Answers 3

4

C# arrays are allocated at runtime on the heap.

C arrays are allocated at compile-time on the stack.
C can also allocate arrays at runtime using malloc. (Just remember to free them when you're done)

Sign up to request clarification or add additional context in comments.

2 Comments

"just remember" is a reason why many programming languages were invented ;)
It should be noted that if malloc has rather little place in C++. (It might be interesting if you really know what you're doing and you're doing micro-optimizations, otherwise) you should use new instead. And you should probably not use bare arrays either (unless you have a good reason). The fact that C++ is (mostly) a superset of C, means in C++ you can do anything you can in C, but you really shouldn't.
3

In c++, you would need to do:

int* a = new int[n];

// Do stuff with the array

delete[] a;

Comments

2

but in c/c++ in wrong

int n; scanf("%d",&n); int a[n]

No! In C99 this code is correct because C99 supports Variable Length Arrays (VLA's).
In C++ the code is ill-formed because the array size must be a constant expression in C++ (although g++ supports VLA as an extension).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.