Comp Sci Declaring arrays statically, on the stack and heap

  • Thread starter Thread starter r0bHadz
  • Start date Start date
  • Tags Tags
    Arrays
AI Thread Summary
Declaring arrays statically in C++ refers to using the static keyword, which allocates memory before the program runs, while stack allocation occurs when local variables are declared within a function. The confusion arises from the terminology, as both static and stack allocations serve different purposes and memory sections. Static arrays retain their values between function calls, whereas stack-allocated arrays are temporary and exist only during the function's execution. Heap memory is dynamically allocated at runtime using functions like malloc() or the new operator. Understanding these distinctions is crucial for effective memory management in C++.
r0bHadz
Messages
194
Reaction score
17
Homework Statement
Write three functions in C++ : one that declares a large array statistically, one
that declares the same large array on the stack, and one that creates the same
large array from the heap . Call each of the subprograms a large number of times
(at least 100000) and output the time required by each
Relevant Equations
no equations
I'm confused here. I guess my professor mean "statically" in the problem, but anyways, I thought, in C++, that declaring an array statically is the as declaring the array on the stack?

For example, if I have a function:

void staticArr(){
int a[10000];
}

here I am declaring an array statically and it is being declared on the stack.

Am I wrong here?

Thanks
 
Physics news on Phys.org
Use the static keyword - either at file scope or within a function.
static int a[10000];
 
.Scott said:
Use the static keyword - either at file scope or within a function.
static int a[10000];
that's the only difference between declaring static and declaring on a stack?

edit: finally found the slide that is suppose to teach me this stuff. I guess I over looked it. You can ignore the above question, I'll be back if I have anymore though.
 
r0bHadz said:
hat's the only difference between declaring static and declaring on a stack?
All three signify different sections of memory, and are used in different ways.
Static memory is allocated before the program starts to run, and is initialized to zero or whatever the equivalent of zero is for the type of the variable.
Heap memory (AKA free store) is allocated at run time by a call to malloc() or similar in C, or by the new or new[] operators in C++. Stack memory is allocated for local variables and function or method parameters.
 

Similar threads

Replies
3
Views
1K
Replies
1
Views
1K
Replies
21
Views
3K
Replies
1
Views
6K
Replies
4
Views
1K
Back
Top