C++ Initialize array pointer - c++

How do I initialize a pointer to a literal array?
I want *grid to point to the new allocated int array {1, 2, 3}.
int *grid = new int[3];
*grid = {1, 2, 3};
thank you.

You can't initialize a dynamically allocated array that way. Neither you can assign to an array(dynamic or static) in that manner. That syntax is only valid when you initialize a static array, i.e.
int a[4] = {2, 5, 6, 4};
What I mean is that even the following is illegal:
int a[4];
a = {1, 2, 3, 4}; //Error
In your case you can do nothing but copy the velue of each element by hand
for (int i = 1; i<=size; ++i)
{
grid[i-1] = i;
}
You might avoid an explicit loop by using stl algorithms but the idea is the same
Some of this may have become legal in C++0x, I am not sure.

#above grid points to the address location where the first element of the array grid[] is stored. Since in C++ arrays are stored in contiguous memory location, you can walk through your array by just incrementing grid and dereferencing it.
But calling grid an (int*) isnt correct though.

I'm not sure if this is obvious but you can do this in one line.
int *grid = new int[3] {1, 2, 3};
Since this is C++ we are talking about you can also split it into
two files. Where your .h file contains:
int *grid;
And your .cpp file contains:
grid = new int[3] {1, 2, 3};

Use the following code, grid is a pointer, grid[] is an element of that pointer.
int grid[] = {1 , 2 , 3};

Related

Memory allocation in C++ STL for dynamic containers

When you declare 2D arrays, they are stored in contiguous memory locations and this is easy as the number of rows is fixed while declaring them.
Whereas when we declare a 2D vector vector<vector<int>> v, how does it work. As the number of rows is not fixed at all. My first guess was the new vector which you push_back into it are randomly allocated but then even that wont work as these vectors of int are randomly accessible.
My first guess is to allocate vectors of int randomly in the memory and store their address in another vector of addresses.
eg
vector<vector<int>> vmain;
vector<int> a = {1, 2, 3};
vector<int> b = {1, 2, 3};
vector<int> c = {1, 2, 3};
vmain.push_back(a);
vmain.push_back(b);
vmain.push_back(c);
is stored something similar to
vector<&vector<int>> vmain; //vector of pointer to vector
vector<int> a = {1, 2, 3};
vector<int> b = {1, 2, 3};
vector<int> c = {1, 2, 3};
vmain.push_back(&a);
vmain.push_back(&b);
vmain.push_back(&c);
Please tell me if this is the correct way.
And also for vector of maps or sets vector<map<int, int>> v1 and vector<set<int>> v2. As size of maps and sets is not fixed.
The vector object doesn't store the elements. It stores a pointer to a contiguous chunk of memory containing the elements. When you have std::vector<std::vector<int>> the outer vector contains a pointer to a contiguous chunk of memory containing vector objects, each of which have a pointer to a contiguous chunk of memory containing the ints.
std::map and std::set also don't store the elements in the object itself. Each object contains a pointer to a BST containing the elements.

How to properly assigning a dynamically create an int and assign it to a dynamic array array with values?

I am working on an assignment for my c++ class where I need to dynamically assign a new int, array, and pointer from another pointer to practice dynamic memory allocation.
At first, I was struggling with creating a new int to provide an int for my new array, but I got it to compile and was wondering if my declarations were correct.
int *dmaArray = new int;
*dmaArray = 4;
I then took that and put it into a dynamically created array, but I don't know how to declare values of the array as it errors out saying "cannot convert to int". I did some thinking and I believe it's because it was declared and needs to be initialized at the declaration; I can't because the declaration is already a declaration (new) in itself.
int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};
A loop wouldn't work to assign values after since the values aren't consecutive or in any pattern. (well, regardless, I would need to use an array because the assignment said so.
This is not how to to declare a dynamic array and initialize it:
int * nodeValues = new int[*dmaArray];
nodeValues[*dmaArray] = {6, 2, 28, 1};
So you declare it this way:
int* nodeValues = new int[dmaArray];
And to assign values to it use loops or manually:
nodeValues[0] = 6;
nodeValues[1] = 2;
nodeValues[2] = 28,
nodeValues[3] = 1;
Remember arrays use indexes to read/write its elements as the fact being some sort of data of the same type contiguous to each other in memory.
So if you want to print the array:
for(auto i(0); i != dmaArray; ++i)
std::cout << nodeValues[i] << ", ";
Finally you should clean memory dynamically allocated after finishing with it because the compiler doesn't do it for you:
delete[] nodeValues;
I figured out how:
int * nodeValues = new int[*dmaArray]{6,5,28,1};

Resizing array, does this code influence it badly in any way?

I've seen bunch of tutorials and threads, but no-one does this to resize an array. My question is, whether this affects bad something in my program or is there better way to resize it?
//GOAL:Array to become {1,2,4,5,6,7,8,9}
int size=9;
int array[size] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 2; i < 8; ++i)
array[i] = array[i + 1];
//ARRAY IS NOW{1, 2, 4, 5, 6, 7, 8, 9, 9}
//GOAL: TO DELETE THAT LAST 9 FROM ARRAY
size=8;
array[size];
//IT SHOULD BE {1,2,4,5,6,7,8,9} now, but does it effect my program in any negative context?
int array[size] declares an array of size elements.
Outside of a declaration, array[size] access element size in array. It does not resize the array. If you do something like that without changing the value of size, it actually tries to access the element after the last element in the array; not a good idea. In this case, since you changed size to be one less than the original, it accesses the last element of the array, which is safe but does not do what you want.
You can not resize an array in C/C++ that is declared on the stack (one allocated on the heap with malloc could be reallocated to a different size, but you'd have trouble copying it as the newly allocated array of the new size is possibly at a completely different memory location; you'd have to save the old one, allocate a new one of the new size, copy the elements you want, and then free the old one.)
If you want something resizeable, you are in C++; use a container (vector, for example, but pick the one that most suits your needs).
And....I just saw arnav-borborah's comment; don't know how I missed that. You can't even declare the array like that, as size is not a compile time constant.
Until size variable is not constexpr, this
int size=9;
int array[size] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
is Variable length array, which is not part of c++ standard, only extension of some compilers.
Also automatic arrays are not resizeable, they have fixed size since declaration until they goes out of scope.
You should use some STL container, like std::array, std::vector.
std::array needs to know size at compile time, so there is the best approach, std::vector, which is easy to use and resizeable.
// #include<vector>
std::vector<int> array { 1,2,3,4,5,6,7,8,9 }; // Uniform initialization
// Remove last element
array.pop_back(); // 'array' has now only 8 elements (1..8)
EDIT
As mentioned in comments, if you want to remove n-th element in vector, you may do
array.erase(array.begin()+n);
and job is done.
Hugely. say if you have a payload of 1GB and you Array.Resize the destination array in chunks of 10k then most of your application CPU and wait states will be resizing that array.
If you pre-allocate the array to 1GB, populating that array will be orders of magnitude faster. This is because every time you use Array.Resize.
The computer needs to move that memory in its entirety to another location in memory just to add the extra length you resized it by.
But of cause if you are dealing with very small arrays. This effect is not noticeable.

Fill an array with incoming integers

I have an array static const unsigned int numbers[] = {1, 2, 3, 4, 5};
From an another loop I am getting integers, how do I fill my array numbers[] with those incoming integers instead?
As you guessed, the "static" part limits it's scope to that
compilation unit. It also provides for static initialization. "const"
just tells the compiler to not let anybody modify it. This variable is
either put in the data or bss segment depending on the architecture,
and might be in memory marked read-only.
More info there
First of all, I never seen assign an array in this way:
numbers[] = test;
Maybe you should study about array.
Maybe you can use this way for copy:
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
or just use simple loop:
for (int i = 0; i < arrayLength; i++) {
array[i] = newValue[i];
}
For more read here
Moreover you declare your array as const that stay for constant, tells you something?
[...]constants are useful for parameters which are used in the program but
are do not need to be changed after the program is compiled.
So I suggest to sudy about const too! Read here

Copy arrays-vectors

This might be too basic, but I would like to ask. I have my code in Java that copies the start array to newStart and assigns the last element to another array.
int[] newStart= Arrays.copyOf(start, start.length + 1);
newStart[start.length] = array[i];
I converted it to my C++ version with vectors as:
vector<int> newStart(5); //Doesnt have to be 5, sth not known
newStart.insert(newStart.end(), start.begin(), start.end());
newStart[start.size()] = array[i];
However, my code doesn't do what I require. That adds the vector one to the other's end, and makes new assignments accordingly. What is the right way to do that?
C++ vectors don't auto-resize on element access (through operator[] nor at method). Replace the last line with either
newStart.push_back(array[i]);
or
newStart.resize(start.size() + 1);
newStart[start.size()] = array[i];
(the former being more efficient, because it does not default-initialize the element first)
I believe Java arrays don't auto-resize either, so I wouldn't expect the Java code to work either (but it will give exception while the C++ code will make daemons fly out of your nose or whatever else nasty the compiler will think of).
Edit: Reading the question again, the code there is actually defined, but the more wrong.
vector<int> newStart(5); //Doesnt have to be 5, sth not known
This statement actually creates a vector that contains 5 (or whatever) default initialized elements, which in case of int is 0. So now you have
{0, 0, 0, 0, 0}
For sake of example let's say start contains {1, 2, 3, 4, 5, 6, 7}.
newStart.insert(newStart.end(), start.begin(), start.end());
vector::insert adds new elements extending the array and moving the following elements as necessary. The insert is before end, so it will append to the vector, resulting in:
{0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7}
I don't think this is what you wanted. It looks like you wanted a copy of start. Which you'd simply create by copy constructing: vector<int> newStart(start).
newStart[start.size()] = array[i];
Now newStart has the initial 5 zeroes and the elements from start, so it's size is start.size() + 5 and therefore it does have index start.size(). It is the 5th element from end. So per above example, this will modify the vector to:
{0, 0, 0, 0, 0, 1, 2, 1, 4, 5, 6, 7}
^
To append start[0] to the end, use push_back as per above.
Also remember, that Java arrays are reference types, where assignment just shares reference to the same array, but C++ vectors are value types where the content is copied on assignment.
I'm a little confused by the mixing of Java and C++. Hopefully one of the explinations below will help.
If you're in C++, vector has an overloaded operator= so you can just type
newvector = oldvector;
and it will copy.
If you're in java, you can use the copy constructor ex:
Vector v2 = new Vector(v1);
Try this:
for (std::vector<int>::iterator it = start.begin() ; it != start.end(); ++it) {
newStart.push_back (*it);
}
Use std::copy algorithm and back_inserter iterator.
Sample code:
#include <iterator>
#include <vector>
#include <algorithm>
int main () {
std::vector<int> src;
std::vector<int> dest;
std::copy(src.begin(),src.end(),back_inserter(dest));
}