Fill an array with incoming integers - c++

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

Related

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};

How to dynamically create a c++ array with known 2nd dimension?

I have a function:
void foo(double[][4]);
which takes a 2d array with 2nd dimension equal to 4. How do I allocate a 2d array so that I can pass it to the function? If I do this:
double * arr[4];
arr = new double[n][4];
where n is not known to the compiler. I cannot get it to compile. If I use a generic 2d dynamic array, the function foo will not take it.
As asked, it is probably best to use a typedef
typedef double four[4];
four *arr; // equivalently double (*arr)[4];
arr = new four[n];
Without the typedef you get to be more cryptic
double (*arr)[4];
arr = new double [n][4];
You should really consider using standard containers (std::vector, etc) or containers of containers though.
typedef double v4[4];
v4* arr = new v4[n];
Consider switching to arrays and vectors though.
I know it may not be what OP has intended to do, but it may help others that need a similar answer.
You are trying to make a dynamic array of statically success array. The STL got your solution: std::vector and std::array
With these containers, things are easy easier:
std::vector<std::array<int, 4>> foo;
// Allocate memory
foo.reserve(8);
// Or instead of 8, you can use some runtime value
foo.reserve(someSize);
// Or did not allocated 8 + someSize, but ensured
// that vector has allocated at least someSize
// Add entries
foo.push_back({1, 2, 3, 4});
// Looping
for (auto&& arr : foo) {
arr[3] = 3;
}
// Access elements
foo[5][2] = 2;
Alternatively to creating a new type and occupying a symbol, you can create a pointer to pointer, and do it like that:
double **arr = new double*[j];
for (int i = 0; i < j; ++i)
{
arr[i] = new double[4];
}
whereas j is the int variable that holds the dynamic value.
I've written a simple code that shows it working, check it out here.

Dynamic memory allocation...how about this type of inititlization?

To create an integer on heap and initialize it to a value 5, we do:
int* a = new int(5);
To create an array of 5 integers on the heap, we do:
int* a = new int[5];
But, if we want to create an array of 5 integers and initialize each of them to 10 in one single instruction, is it possible?
To make things more interesting, let us say that the array size will only be known at run time. How about then?
Also, I know this is a very trivial question, but I'm making this transition from Java and get confused at times with C++, so... if not initialized during declaration, then unlike in Java, C++ primitive data types are not initialized with default values, and contain garbage values, right?
But someone told me that if they are declared as global variables, then they are initialized to default values like in Java...is that true as well? Why?
I prefer:
std::vector<int> a = {10,10,10,10,10};
C++ is a very complex language, with many different (even contradicting) goals.
One of the ideas behind it was that you should not pay in efficiency what you don't need and this is what is behind the concept of uninitialized values.
When you write
int x;
the variable x is initialized if it's at global/namespace scope and instead is not initialized when the definition is in a local scope.
This happens not because who designed C is crazy (of course an initialized value is better) but because initialization at global/namespace scope is free from an efficiency point of view as it's done compile/link/loading time, not at runtime.
Initializing a variable in local scope instead has a cost (small, but non-zero) and C++ inherited from C the idea that shouldn't pay for it if you don't need it, thus if you want your variable initialized to any value simply says so with:
int x = 42;
Note however that an uninitialized variable is not simply "containing a garbage value", it's uninitialized and you are not allowed to read its content as such an operation is "undefined behavior".
There are platforms in which just reading the content of an uninitialized variable may crash ("trap representations": for example hardware with dedicated registers for pointers in which just placing an invalid address in a register - not doing anything with it - provokes an hardware exception).
No, it is not possible to allocate an array with new[] and specify an initial value for the array elements. You have to fill in the array after the allocation is finished, eg:
int count = 5;
int* a = new int[count];
for (int i = 0; i < count; ++i)
a[i] = 10;
...
delete[] a;
That is not very C++-ish. You could use std::fill() to get rid of the loop, at least:
int count = 5;
int* a = new int[count];
std::fill(a, a+count, 10);
...
delete[] a;
A better option is to switch to a std::vector instead, which has a constructor that does exactly what you are looking for:
std::vector<int> a(5, 10); // create 5 elements initialized to value 10
std::vector has a constructor where you can specify the initial size and initial value:
std::vector<int> an_array(size, init_value);
If you want to use a dynamic array using new[], you have to assign the initial value to each element:
int* array = new a[size];
for(int i = 0; i < size; ++i)
array[i] = init_value;
...
delete[] array;
Use std::array if the size is known at compile-time:
std::array<int, 5> myArray = { 1, 2, 3, 4, 5 };
Which is RAII-conform and safe.
You just have to include <array> and <initializer_list>.
In other cases, use std::vector.
This works for me with g++ 4.8.2.
#include <iostream>
int main()
{
int* a = new int[5]{10, 10, 10, 10, 10};
for ( int i = 0; i < 5; ++i )
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
}
Output:
10 10 10 10 10
Update, in response to OP's comment
When you use
std::vector<int> v(5, 10);
the constructor of std::vector used is:
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
Let's say you have a class
class MyClass
{
public:
MyClass(int ) {}
};
You can construct a std::vector<MyClass> using:
std::vector<MyClass> v(10, MyClass(50));
or
std::vector<MyClass> v(10, 50);
In the second case, the compiler knows how to implicitly construct a temporary MyClass object given the argument 50 alone. But either way, a temporary MyClass object is being passed to the vector, and that is OK because the argument type of that parameter is const MyClass&, which can bind to a temporary object.

C++ Pointer of Array of Ints Initialization

I want to have an array accessible by all functions of a class.
I put the array as private variable in the header file.
private:
int* arrayName;
In the .cpp file where I implement the class, the constructor takes in an int value (size) and creates the array. The goal is to fill it up
ClassName::ClassName(int numElements){
arrayName = new int[numElements]; //make arrays the size of numElements
for(int i = 0; i<numElements; i++)
arrayName[i] = 0;
}
I feel like this is quite inefficient. I know you can do int array[5] = {0}; but how do you do it when you don't initially know the size.
If you want to zero-initialize a newed array, just do value-initialize it. This has the effect of zero-initializing its elements:
arrayName = new int[numElements]();
// ^^
But you really want to be using an std::vector<int>.
private:
std::vector<int> vname;
and
ClassName::ClassName(int numElements) : vname(numElements) {}
This way you don't have to worry about deleting an array and implementing copy constructors and assignment operators.
You can use the memset function:
memset(arrayName,0,sizeof(int)*numElements);
This void * memset ( void * ptr, int value, size_t num ); function sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
To use it you must include the string.h header file.
For more information: http://www.cplusplus.com/reference/cstring/memset/
What you want to do is progressively expand the array on demand.
arrayName = new int[numElements];
for(int i = 0; i<numElements; i++)
arrayName[i] = 0;
The above code (what you gave) will give you an array of size numElements, and THEN the for loop will fill it. This is allocated now, and can't, as I understand it, be simply or easily resized (memset will overwrite previously held values in the array).
You could copy the whole array over every time you want to resize it:
int * oldarr = new int[OldSize];
//fill your old array
int * newarr = new int[NewSize];
for(int i = 0; i<OldSize; i++)
newarr[i] = oldarr[i];
Other than that, you could make the array much larger, or you could use various STLs, such as std::vector. Vector can be increased with a simple push_back function, and allows [] operator access (like arr[5] and whatnot).
Hope this helps!

constructing variable name from a variable in c++

I have lots of arrays with different sizes so they can't be multidimensional array as far as i know, so i named them as follows:
arr1[]
arr2[]
arr3[]
arr4[]
...
now can i use for loop to go over them and access them...
for(int i=1; i<5; i++) {
for(int j=o; i<etc; j++) {
cout<<arr[i][[j]<<endl;
}
}
or cout<<arr+i<<endl;
now this obviously is telling compiler to add arr and i together, but that is not what i want. I want it to print arr1, arr2, etc.
I have tried, putting dot, comma, slashes, etc.
No. You do need an array here. More specifically, you need a heterogenous container.
With the magic of indirection, you can actually use a homogenous container at the C++ level to achieve these semantics:
std::vector<std::vector<WhateverYourTypeIs>> v;
If you really need only five in the outer array, this will do the job:
std::array<std::vector<WhateverYourTypeIs>, 5> a;
and will simplify your code.
If you are really forced to use plain arrays (and only then), consider using an array of pointers too:
int* const array[] = {arr1, arr2, arr3, arr4, ...};
Thus, you get a pointer to the first element of array arr# with array+#.
You might want a companion-array storing the element counts, too:
size_t carray[] = {sizeof arr1/sizeof *arr1, sizeof arr1/sizeof *arr2,
sizeof arr1/sizeof *arr3, sizeof arr1/sizeof *arr4, ...};
Also, look at this for a safer way to get the element-count of an array:
template<size_t N, class T>
constexpr size_t element_count(T (&arr)[N])
{return N;}
You are confusing compile/build time and runtime. I would suppose to use only runtime objects like arrays/vectors.
But you could also use macros or variable argument lists:
http://www.cprogramming.com/tutorial/c/lesson17.html