answersLogoWhite

0


Best Answer

For any given type, T, a definition of type T[n] will allocate an array of n elements of type T in contiguous memory, for all n>=0. The total size of the allocation will be equivalent to n * sizeof(T). Elements of type T can be accessed by index, in the range 0 to n-1. These indices allow the compiler to compute the offset from the start of the array, such that index i refers to the address i * sizeof(T).

Arrays can be either fixed-size or variable-length and can be allocated on the stack or the heap but only fixed-size arrays can be allocated statically. The following shows all the possibilities:

int a[10]; // fixed-size, static allocation, global scope

void f(int n) {

int b[10]; // fixed-size, stack allocation, local scope

int c[n]; // variable-length, stack allocation, local scope

int* d = new int[10]; //fixed-size, heap allocation

int* e = new int[n]; // variable-length, heap allocation

// ...

delete [] e;

delete [] d;

}

Note that the arrays referred to by the pointers d and e are anonymous arrays (as are all heap allocations). It is important that we maintain at least one reference to a heap allocation in order to release that memory back to the system when we no longer require it. The pointers d and e will automatically fall from scope when the function ends, but the memory they refer to remains, unless we explicitly delete that memory. Ideally, the function that allocates heap memory should also release that memory, however so long as we maintain a reference to that memory (such as through a global pointer), any function can release it. This can lead to problems such as resource leaks as ownership of the memory is unspecified; any code can take ownership of the memory at any time. This is particularly problematic in multi-threaded applications where two threads may attempt to take ownership at the same time. If one thread releases the memory while another is still accessing that memory, undefined behaviour will occur. To avoid this, pointers to heap allocations are best encapsulated within a resource handle, a class that takes ownership of the memory. In C++, std::vector provides a thread-safe resource handle to variable-length arrays.

User Avatar

Wiki User

8y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

14y ago

Should be allocated, before you first use it.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How memory is allocated for array type variable?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Where the Memory is allocated for a variable in a program?

if a variable is of value type memory is allocated on stack memory.. if it is of reference type,memory is allocated on heap memory..


When is memory allocated when declaring an array in C plus plus?

It depends how the array is declared (fixed size or variable size) and where it is declared (global scope or local scope). If the array is declared in global scope (outside a function) and is fixed size, it will be allocated in static memory. If it is variable size, the pointer is stored in static memory while the array itself is allocated on the heap. The pointer in static memory points to the start address of the array in heap memory. If the array is declared in local scope (inside a function) and is fixed size, it will be allocated on the stack in whichever thread the function was called. If it is variable size, the local pointer is stored on the stack while the array is allocated on the heap. The pointer will fall from scope when the function returns so the array must not be allowed to outlive the function in which the pointer is declared. If the array must outlive the function that allocates the array, the pointer must be declared at a higher scope in the call stack and must be passed by reference to or returned by value from the function that allocates the array. If you provide your own memory manager, however, an array may be allocated wherever the memory manager's memory pool is allocated, be it in static memory, the stack or the heap. A memory manager essentially allocates an array of bytes which you can then utilise as you see fit (the array of bytes will be allocated as per the previous description for arrays in general).


Do reference variables occupy memory in c?

All references must be non-null, therefore they will always have memory allocated to them. A reference is simply a non-null memory location that stores a specific type of variable, as determined by the reference's type. The reference name is an alias (a token) for the memory location, in much the same way that an array name is an alias for the starting address of the array. A pointer variable is different in that memory must be set aside for the pointer variable itself, in addition to the memory it actually points to. On a 32-bit system, 4 bytes must be allocated to every pointer variable, to store the memory address that they point to, which could be null. But references only occupy the memory they actually refer to, which can never be null (a null reference will in fact render the program invalid).


Where the local variables will be stored?

When you declare a variable and it's data type in a function, it is stored in the specific space for memory allocated by the variable type identifier known as the "stack."


How do arrays differ from single memory position variables?

A single memory position variable can store only one value of its type. An array can store n number of values, where n is the size of the array.

Related questions

Where the Memory is allocated for a variable in a program?

if a variable is of value type memory is allocated on stack memory.. if it is of reference type,memory is allocated on heap memory..


When is memory allocated when declaring an array in C plus plus?

It depends how the array is declared (fixed size or variable size) and where it is declared (global scope or local scope). If the array is declared in global scope (outside a function) and is fixed size, it will be allocated in static memory. If it is variable size, the pointer is stored in static memory while the array itself is allocated on the heap. The pointer in static memory points to the start address of the array in heap memory. If the array is declared in local scope (inside a function) and is fixed size, it will be allocated on the stack in whichever thread the function was called. If it is variable size, the local pointer is stored on the stack while the array is allocated on the heap. The pointer will fall from scope when the function returns so the array must not be allowed to outlive the function in which the pointer is declared. If the array must outlive the function that allocates the array, the pointer must be declared at a higher scope in the call stack and must be passed by reference to or returned by value from the function that allocates the array. If you provide your own memory manager, however, an array may be allocated wherever the memory manager's memory pool is allocated, be it in static memory, the stack or the heap. A memory manager essentially allocates an array of bytes which you can then utilise as you see fit (the array of bytes will be allocated as per the previous description for arrays in general).


What an array?

An array is an aggregate of data elements of the same type. Arrays are allocated in contiguous memory. An element of an array can be another array type, also known as a multi-dimensional array.


Do reference variables occupy memory in c?

All references must be non-null, therefore they will always have memory allocated to them. A reference is simply a non-null memory location that stores a specific type of variable, as determined by the reference's type. The reference name is an alias (a token) for the memory location, in much the same way that an array name is an alias for the starting address of the array. A pointer variable is different in that memory must be set aside for the pointer variable itself, in addition to the memory it actually points to. On a 32-bit system, 4 bytes must be allocated to every pointer variable, to store the memory address that they point to, which could be null. But references only occupy the memory they actually refer to, which can never be null (a null reference will in fact render the program invalid).


Where the local variables will be stored?

When you declare a variable and it's data type in a function, it is stored in the specific space for memory allocated by the variable type identifier known as the "stack."


When does an array behave like a pointer in C plus plus -- provide sample code to support each case?

An array never behaves like a pointer.Understand that a pointer is a variable -- no different to any other variable, other than its type. like any other variable, it is allocated its own memory (4 bytes in a 32-bit system). Those 4 bytes can store any 32-bit value, from 0x00000000 to 0xFFFFFFFF, but because it is declared to be a pointer, that value actually represents a memory location, somewhere within the 4GB address space. 0x00000000 is a reserved memory location -- what we refer to as NULL.An array is not the same as a pointer in any sense. The array name refers to the actual memory (the starting address) where the array resides. But the array name is not a variable -- unlike a pointer, it is not separate from the memory it refers to -- it is merely an alias that refers to the memory allocated to the array itself.That said, pointers and arrays can appear to be the same. For instance, the strlen() function expects you to pass a const char pointer, and yet you can pass an array name instead and it works just fine:char cArray[12];char * p = cArray;strlen( p ); // Pass a pointerstrlen( &cArray[0] ); // Pass pointer to array element via AddressOf operatorstrlen( cArray ); // Pass an array nameAll three of these functions work exactly the same so it would be easy to assume the array is a type of pointer. But it is not. To understand what's really going on here you have to understand how pointers and arrays are actually passed to function.When you pass a pointer to a function, you don't pass the pointer itself, you pass the memory address stored in the memory allocated to the pointer. In other words, pointers are passed by value, not by reference. Similarly, when you pass an array name, you pass the starting address of the array.That's all there is to it! The function's parameter, a pointer, is allocated its own memory. It is a temporary variable, local to the function. All it expects is a memory location so whether you pass a pointer or an array name, that's exactly what it receives.


What are variables in c programming?

A variable in C programming is a memory allocation where a value may be stored and mutated. Rather than referencing the memory allocation by its physical address, we give it an easy-to-remember name. Each variable also has a type associated with. This tells the compiler how many bytes are allocated to the variable and how those bytes are to be interpreted. That is; the same binary representation has a different meaning depending upon the type. A pointer is also a variable. We use a pointer variable to store a memory address and thus refer to that address being pointed at. We can also dereference that address and thus indirectly access the value stored at that address. Pointers make it possible for the same algorithms to refer to different memory addresses, allowing those algorithms to operate upon the values themselves. Without pointer variables, algorithms would only be able to operate upon copies of those values. An array is a sequence of variables of the same type arranged in contiguous memory. These variables do not have names (they are anonymous) however we can refer to them through a zero-based index. The array name provides a reference to the start of the array and the array type determines how many bytes each element occupies, thus multiplying the index by the type's length determines the offset memory address of each indexed element in the array. The only thing we cannot determine is how many elements are allocated to the array; it is up to the programmer to maintain a count of elements using a separate variable; incrementing or decrementing the count each time the array is re-allocated. Arrays cannot be passed to or returned from functions. This is because an array implicitly converts to a pointer variable when passed to a function. In order for the function to treat this pointer as an array, we must also pass the array's length. A constant is the same as a variable except constants are not mutable. The seemingly contradictory term "constant variable" is sometimes used, however this specifically refers to a constant that falls from scope and is subsequently re-instantiated with a new value, as will happen when a function's formal argument is declared constant or when constant memory is allocated on the heap. Formal arguments are always allocated on the call stack and will fall from scope when the function returns. Global and local constants, however, are allocated in static memory (in the program's data segment) and will remain in scope throughout the program's life cycle. All constants must be assigned a value at the point of instantiation (when they come into scope) and that value cannot be changed while the constant remains in scope.


How do arrays differ from single memory position variables?

A single memory position variable can store only one value of its type. An array can store n number of values, where n is the size of the array.


What is the importance of array?

Arrays are important because we often need to work with a collection of variables of the same type and, particularly with large collections, it would be impractical to declare and name each one individually. With an array we don't have to name them because the variables are allocated in contiguous memory addresses and every element is the same length. Knowing only the start address of the array and the zero-based index of an element we gain constant-time random access to any element in the array. An array is really just an extension of a type. When we declare a variable of a given type we allocate sufficient memory to hold just one object of that type. With an array, we can allocate as many objects as we require.


How can you increase the size of a statically allocated array?

/* Allocate space for an array with ten elements of type int. */int *ptr = malloc(10 * sizeof (int));if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */ realloc It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is void *realloc(void *pointer, size_t size);


The elements in an array must be of the same basic data type but why must they be stored in contiguous memory?

An array is nothing more than a block of contiguous memory addresses divided into one or more units of equal length. We call these units elements. As a result, all elements of an array must be allocated contiguously. Other than padding for memory alignment purposes, an array offers the most compact storage for multiple elements of the same type. And because the elements are allocated contiguously, it is trivial to traverse the array from one element to the next using nothing more than a pointer variable of the same type as the array. Each increment or decrement of the pointer increases or decreases the address by 1 element. The array suffix operator [] does the same thing, except the index is a zero-based offset from the start of the array. The first element is index 0 because it is 0 elements from the start of the array while the nth element is found at index n-1. When we create an array we have the choice of storing the objects themselves in the array or storing a pointer to the objects. With the latter, the objects need not be allocated contiguously, however we consume more memory because the array of pointers consumes additional memory that we wouldn't need to consume were all the objects allocated in the array itself. We also have the additional cost of dereferencing those pointers in order to access the objects being referred to. However, arrays of pointers are advantageous when the objects are larger than a pointer (in bytes) or are of polymorphic type. Copying or moving a large object in memory is more expensive than copying or moving a pointer, so if we need to sort an array of large objects, an array of pointers is generally more efficient despite the indirection. But with polymorphic types we have to use pointers because polymorphic types are not guaranteed to be the same length so we must store a pointer to the common base type if we wish to retain polymorphic behaviour.


What construct can you use to define an array?

For any type T, the type T[n] instantiates an array of n elements of type T, where n is a constant expression. int a[100]; // a fixed-length array of 100 integers (allocated in static memory) void f (const int n) { int b[n]; // a fixed-length array of n integers (allocated on the stack) // ... } If the number of Ts in an array could change at runtime, we can allocate memory on the heap instead: void g (int n) { int* ptr = malloc (n * sizeof(int)); // allocate n integers on the heap ptr[0] = 42; // access memory using suffix notation // ... n *= 2; // double the size of the array ptr = realloc (ptr, n * sizeof (int)); // reallocate (allocation may move to new memory) assert (nptr[0]==42); // assert that existing values are retained even after a reallocation // ... free (ptr); // don't forget to release memory when it is no longer required! }