How to Create a Dynamic Array of Integers

How to create a dynamic array of integers

int main()
{
int size;

std::cin >> size;

int *array = new int[size];

delete [] array;

return 0;
}

Don't forget to delete every array you allocate with new.

Dynamically create an integer array

According to your question if want to create dynamic size array then use

int array[]=new int[size_of_array];

And if create ArrayList then it is already a dynamic size no need to specified size.

ArrayList<Integer> array = new ArrayList<>(size_of_array);

if you do this then you are defining capacity of ArrayList which is auto increment when initial capacity is full.

and when you add elements in your list like

array.add(45);

then its size increase and it not show you 0.

How do I create a dynamic array with real numbers?

As the error message suggests, double n; cannot be used as the number of elements, which must be an integer. It should be int n;.

Dynamic array of array of int in C

One way is just to declare for example a pointer in a file scope like

int ( *array )[2] = NULL;

and then in one of functions allocate a memory for the array.
For example

#include <stdlib.h>

int (*array)[2] = NULL;

int main(void)
{
int numberofargs = 5;
array = malloc( sizeof( int[numberofargs][2] ) );

//...

free( array );

return 0;
}

Or the following way

#include <stdlib.h>

int **array = NULL;

int main(void)
{
int numberofargs = 5;

array = malloc( numberofargs * sizeof( *array ) );


for ( int i = 0; i < numberofargs; i++ )
{
array[i] = malloc( sizeof( *array[i] ) );
}

//...

for ( int i = 0; i < numberofargs; i++ )
{
free( array[i] );
}
free( array );

return 0;
}

Dynamic array of Linear search funcion implementation

At very first I join in the std::vector recommendation in the question's comments (pass it as const reference to avoid unnecessary copy!), that solves all of your issues:

std::vector<size_t> linearSearch(std::vector<int> const& array, int value)
{
std::vector<size_t> occurrences;
// to prevent unnecessary re-allocations, which are expensive,
// one should reserve sufficient space in advance
occurrences.reserve(array.size());
// if you expect only few occurrences you might reserve a bit less,
// maybe half or quarter of array's size, then in general you use
// less memory but in few cases you still re-allocate

for(auto i = array.begin(); i != array.end(); ++i)
{
if(*i == value)
{
// as using iterators, need to calculate the distance:
occurrences.push_back(i - array.begin());
}
}
return occurences;
}

Alternatively you could iterate with a size_t i variable from 0 to array.size(), compare array[i] == value and push_back(i); – that's equivalent, so select whichever you like better...

If you cannot use std::vector for whatever reason you need to be aware of a few issues:

You indeed can get the length of an array by sizeof(array)/sizeof(*array) – but that only works as long as you have direct access to that array. In most other cases (including passing them to functions) arrays decay to pointers and these do not retain any size information, thus this trick won't work any more, you'd always get sizeOfPointer/sizeOfUnderlyingType, on typical modern 64-bit hardware that would be 8/4 = 2 for int* – no matter how long the array originally was.

So you need to pass the size of the array in an additional parameter, e.g.:

size_t* linearSearch
(
int* array,
size_t number, // of elements in the array
int value // to search for
);

Similarly you need to return the number of occurrences of the searched value by some means. There are several options for:

  1. Turn num into a reference (size_t& num), then you can modify it inside the function and the change gets visible outside. Usage of the function get's a bit inconvenient, though, as you need to explicitly define a variable for:
size_t num = sizeof(array)/sizeof(*array);
auto occurrences = linearSearch(array, num, 7);

  1. Append a sentinel value to the array, which might be the array size or probably better maximum value for size_t – with all the disadvantages you have with C strings as well (mainly having to iterate over the result array to detect the number of occurences).
  2. Prepend the number of occurrences to the array – somehow ugly as well as you mix different kind of information into one and the same array.
  3. Return result pointer and size in a custom struct of yours or in e.g. a std::pair<size_t, size_t*>. You could even use that in a structured binding expression when calling the function:
auto [num, occurences] = linearSearch(array, sizeof(array)/sizeof(*array), 7);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// here the trick yet works provided the array is declared above the call, too,
// as is in your example

Option 4 would be my personal recommendation out of these.

Side note: I switched to size_t for return values as negative indices into an array are meaningless anyway (unless you intend to use these as sentinel values, e. g. -1 for end of occurrences in option 2).

How to initialize a dynamic int array elements to 0 in C

In this case you would use calloc():

array = (int*) calloc(n, sizeof(int));

It's safe to assume that all systems now have all zero bits as the representation for zero.

§6.2.6.2 guarantees this to work:

For any integer type, the object representation where all the bits are
zero shall be a representation of the value zero in that type.

It's also possible to do a combination of malloc() + memset(), but for reasons discussed in the comments of this answer, it is likely to be more efficient to use calloc().

C++ Creating Dynamic 2D Array With One Statement but Without auto

C++ does not support dynamically-sized raw arrays (aka Variable Length Arrays, or VLAs). Whenever you come across the need for such a dynamic array (how ever many dimensions it may have), you should be immediately thinking of using the std::vector container.

Once properly created, you can use the [] operator (concatenated, for 2-D vectors) in much the same way as you would with raw arrays.

Here's a short code demo that creates a dynamic, 2-dimensional 'array' of integers, using the std::vector class, and initializes all elements with an especially significant, non-zero value:

#include <iostream>
#include <vector>

int main()
{
size_t nCols, nRows;
std::cout << "Enter nRows and nCols: ";
std::cin >> nRows >> nCols;
if (nCols < 2 || nRows < 2) {
std::cout << "Matrix is too small!\n";
return 1;
}
// The following SINGLE LINE declares and initializes the matrix...
std::vector<std::vector<int>> arr(nRows, std::vector<int>(nCols, 42));
std::cout << "nRows = " << arr.size() << "\n";
std::cout << "nCols = " << arr[0].size() << "\n";
for (auto& row : arr) {
for (auto i : row) {
std::cout << i << " ";
}
std::cout << std::endl;
}
// Demo for how to use the "[][]" operator ...
arr[0][0] = arr[nRows - 1][nCols - 1] = 33; // Change 1st and last
std::cout << "------------\n";
for (auto& row : arr) {
for (auto i : row) {
std::cout << i << " ";
}
std::cout << std::endl;
}
return 0;
}

One of the great benefits of using std::vector over new[] is that you don't have to worry about subsequently calling delete[] – the container class takes care of all memory allocation and deallocation internally.



Related Topics



Leave a reply



Submit