Let's say I have these 10 previously declared arrays in my code.
int arr1[] = {1,2,3,4,5,6,7,8,9,10};
int arr2[] = {1,2,3,4,5,6,7,8,9,10};
int arr3[] = {1,2,3,4,5,6,7,8,9,10};
int arr4[] = {1,2,3,4,5,6,7,8,9,10};
int arr5[] = {1,2,3,4,5,6,7,8,9,10};
int arr6[] = {1,2,3,4,5,6,7,8,9,10};
int arr7[] = {1,2,3,4,5,6,7,8,9,10};
int arr8[] = {1,2,3,4,5,6,7,8,9,10};
int arr9[] = {1,2,3,4,5,6,7,8,9,10};
int arr10[] = {1,2,3,4,5,6,7,8,9,10};
Basically, I want to append all 10 of these arrays one after another to make one single array.
ArrayOfArrays = { arr1[], arr2[], arr3[], arr4[], arr5[], arr6[], arr7[], arr8[], arr9[], arr10[] }
How would I go about doing this? This question might seem trivial for some, but I'm new to C++ and can not figure out how to do it. Please help and thanks in advance.
Basically, I want to append all 10 of these arrays one after another to make one single array.
You cannot do that.
The closest you can get to that is by using std::array.
std::array<int, 10> arr1 = {1,2,3,4,5,6,7,8,9,10};
...
std::array<int, 10> arr10 = {1,2,3,4,5,6,7,8,9,10};
std::array<std::array<int, 10>, 10> arrayOfArray = {arr1, ..., arr10};
Try this approach:
#include <iostream>
#include <vector>
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int arr2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// ...other arrays here...
// We pass a reference to a vector and return the same vector for performance reasons.
// Compiler often can optimize that into a better code.
std::vector<int> append(std::vector<int> & vec, int * data, int size)
{
for (int i = 0; i < size; ++i)
vec.push_back(data[i]);
return vec;
}
int main()
{
std::vector<int> data;
data = append(data, arr1, 10);
data = append(data, arr2, 10);
for (auto i : data)
std::cout << i << ", ";
std::cout << std::endl;
return 0;
}
Also, in C++ there are good containers for storing arrays, try searching for std::array and std::vector containers. First is a fixed size static array, the other one is dynamic.
I want to append all 10 of these arrays one after another to make one
single array ?
You can have array of pointers like
int *ArrayOfPointers[10] = { &arr1, &arr2, &arr3, &arr4, &arr5, &arr6, &arr7, &arr8, &arr9, &arr10};
Here ArrayOfPointers is array of 10 int pointers i.e it can store address of 10 one dimension int array like arr1, arr2 etc.
I assume there may be better method than what I'm suggesting in advance C++ for the same task.
In C++ it is unnecessary and ill-advised to use C-style arrays. For arrays of
constant size you may use std::array
and for arrays of variable size, std::vector
It looks rather as if what you actually want is a constant two-dimensional matrix
and to be able to access each of its rows as as a constant array, but do not
know how to initialise a two-dimensional matrix. If that's the case, here's how:
#include <iostream>
#include <array>
std::array<std::array<int,10>,10> matrix = {{
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}},
{{1,2,3,4,5,6,7,8,9,10}}
}};
int main()
{
std::array<int,10> const & arr0 = matrix[0];
for (int const & i : arr0) {
std::cout << i << ' ';
}
std::cout << std::endl;
// Or more simply...
auto const & arr5 = matrix[5];
for (auto const & i : arr5) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
Compile, link and run:
$ g++ -Wall -Wextra main.cpp && ./a.out
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
live demo
I have a header, cpp and main class.
//Arr.h
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
//Arr.cpp
#include "Arr.h"
#include <iostream>
using namespace std;
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
However, when I run the code, a.printArr() prints out array address and not the values contained in the array. Is there a way to fix this?
Your code will print not address but some indeterminate value generated via default-initializing. Initialize the member array instead of the local array to throw away.
void Arr::setArr()
{
x[0] = 2;
x[1] = 3;
x[2] = 5;
x[3] = 7;
x[4] = 11;
}
Your problem is here:
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
the declaration int x[5] defines a new array of 5 elements which will be destroyed on exiting that function; and the name x hides the data member Arr::x.
One way you can do it is this:
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
Full code:
#include <iostream>
#include <algorithm>
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
using namespace std;
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
Your code is not printing array address. Maybe you saw some unexpected numbers and assumed it was an address, but in fact it is undefined behaviour caused by outputting uninitialized variables.
Your code int x[5] = .... failed because this declares a new local variable x, it doesn't modify the class member x.
Perhaps you tried:
x = { 2, 3, 5, 7, 11 };
and got compilation errors. This is because C-style arrays may not be assigned. This annoying rule is a hangover from C++'s past. To avoid this problem and many others, you can try to avoid using C-style arrays. In this case use a C++ array:
private:
std::array<int, 5> x;
Then the suggested assignment will work.
As WhiZTiM has already pointed out, your problem is at the setArr function in your class. The reason for this is because in C++ you cannot assign values to the array in the "normal fashion" i.e. using x = {blah, blah, blah}; (unless you use std::array<int, ARRAYSIZE>). In setArr you are creating another array named x and then this array is deleted once it is out of scope, and in printArr you are printing an array with no values in it yet.
Each value in the array must be set individually in C styled arrays (as shown in MikeCAT's answer).
One solution to this is to create a temporary array with the values you want and assigning the values to your class array through a for loop, i.e.:
void Arr::setArr() {
const int ARRAYSIZE = 5;
int tmp[ARRAYSIZE] = {2, 3, 5, 7, 11};
for (int i = 0; i < ARRAYSIZE; ++i) {
x[i] = tmp[i];
}
}
As M.M also pointed out, can simply change int x[5] in your private variables in Arr to std::array<int, 5> x and then in setArr simply have the statement: x = {2, 3, 5, 7, 11}; which is the better option in my opinion and easier to read, but it's also good to know how to use C arrays 😊
I am trying to declare an array of pointers each of which points to int arrays of different sizes. Any ideas?
From your description it sounds like you are looking for a pointer to a pointer.
int **aofa;
aofa = malloc(sizeof(int*) * NUM_ARRAYS);
for (int i = 0 ; i != NUM_ARRAYS ; i++) {
aofa[i] = malloc(sizeof(int) * getNumItemsInArray(i));
}
for (int i = 0 ; i != NUM_ARRAYS ; i++) {
for (int j = 0 ; j != getNumItemsInArray(i) ; j++) {
aofa[i][j] = i + j;
}
}
NUM_ARRAYS arrays may have different number of elements, as determined by the value returned by the getNumItemsInArray(i) function.
int* ar[2];
int ar1[] = {1,2, 3};
int ar2[] = {5, 6, 7, 8, 9, 10};
ar[0] = ar1;
ar[1] = ar2;
cout << ar[1][2];
C version, should help clarifying the different types of declarations:
#include <stdio.h>
int main()
{
/* let's make the arrays first */
int array_A[3] = {1, 2, 3};
int array_B[3] = {4, 5, 6};
int array_C[3] = {7, 8, 9};
/* now let's declare some pointers to such arrays: */
int (*pA)[3] = &array_A;
int (*pB)[3] = &array_B;
int (*pC)[3] = &array_C; /* notice the difference: */
/* int *pA[3] would be an array of 3 pointers to int because the [] operator*/
/* has a higher precedence than *(pointer) operator. so the statement would */
/* read: array_of_3 elements of type_pointer_to_int */
/* BUT, "int (*pA)[3]" is read: pointer_A (points to) type_array_of_3_ints! */
/* so now we need a different array to hold these pointers: */
/* this is called an_ARRAY_of_3_pointers to_type_array_of_3_ints */
int (*ARRAY[3])[3] = {pA, pB, pC};
/* along with a a double pointer to type_array_of_3_ints: */
int (**PTR)[3] = ARRAY;
/* and check that PTR now points to the first element of ARRAY: */
if (*PTR == pA) printf("PTR points to the first pointer from ARRAY \n");
PTR++;
if (*PTR == pB) printf("PTR points to the second pointer from ARRAY! YAY!\n");
return 0;
}
> $ clang prog.c -Wall -Wextra -std=gnu89 "-ansi" output:
> PTR points to the first pointer from ARRAY
> PTR points to the second pointer from ARRAY! YAY!
Check out the section "Pointers to Arrays of Objects"
http://www.functionx.com/cpp/Lesson24.htm
It might help you.
In C++ you can declare it like shown below.new operator can work like similar to malloc in C.
int** array = new int*[n];
#include <iostream>
using namespace std;
#define arraySize 3
const int arr1[] = {48,49,50};
const int arr2[] = {64,65,66};
const int arr3[] = {67,68,69};
typedef const int (*arrayByte);
arrayByte arrayPointer[arraySize] = {
arr1,arr2,arr3
};
void printArr(const int arr[], int size){
for(uint8_t x=0;x<size;x++){
printf("value%d=%d \n",x,arr[x]);
}
}
int main()
{
printf("Print Array 0\n");
printArr(arrayPointer[0],arraySize);
printf("Print Array 1\n");
printArr(arrayPointer[1],arraySize);
printf("Print Array 2\n");
printArr(arrayPointer[2],arraySize);
return 0;
}
try this code: C++ online
This is essentially what I'm trying to do, but not the actual source code.
namespace namespace {
int array [3];
}
namespace::array={1,2,3}
my gcc asks for an expression, and I'm not sure of what to do. Must I namespace::array[1]; each individual element?
You can only use an initializer list in a definition:
int array[3] = { 1, 2, 3 };
If you use:
int array[3];
then you need to initialize the array in a function, using
array[0] = 1;
array[1] = 2;
array[2] = 3;
Although it an odd mixture of C99 and C++, gcc allows this:
#include <string.h>
int a[3];
int main()
{
memcpy(a, (int[3]){ 1, 2, 3}, sizeof(a));
}
!
How about namespace ns { int array[3] = {1, 2, 3}; }?
There are several ways:
1) Explicitly set values for each element:
namespace ns {
int array [3];
}
ns::array[0]=1;
ns::array[1]=2;
ns::array[2]=3;
\\ or if they should contain consequtive values:
\\ for (size_t i = 0; i < 3; ++i)
\\ ns::array[i] = i + 1;
2) If you want initialize static array in place of its declaration, then you could move it initializer list as follows:
namespace ns {
int array[3] = {1, 2, 3};
}
3) Use typedef:
namespace ns {
typedef int array_t[3];
}
ns::array_t array = {1, 2, 3};
3) Also you can make some research of std::tr1::array, which may be used as such:
std::tr1::array<int, 3> arr = {1, 2, 3};
I want to initialize an array and then initialize a pointer to that array.
int *pointer;
pointer = new int[4] = {3,4,2,6};
delete[] pointer;
pointer = new int[4] = {2,7,3,8};
delete[] pointer;
How can I do this?
Why not use
int array[4] = {3, 4, 2, 6};
Is there a reason you want to allocate memory for the array from heap?
Suggestion after comment:
int arrays[32][4] = {{3, 4, 2, 6}, {3, 4, 1, 2}, ...}
int *pointers[4];
pointers[0] = arrays[0];
pointers[1] = arrays[12];
pointers[2] = arrays[25];
pointers[3] = arrays[13];
...
pointers[0] = arrays[13];
pointers[1] = arrays[11];
pointers[2] = arrays[21];
pointers[3] = arrays[6];
int *pointer = new int[4]{3,4,2,6};
EDIT: As pointed out in the comments, this is C++0x syntax. To do this in earlier versions, write a function that takes a stack array + size, allocates a new array on the heap, loops through the stack array populating the heap array, and then returning a pointer to the heap array.
int* foo( const int size, int *array )
{
int *newArray = new int[size];
for( int index = 0; index < size; ++index )
{
newArray[index] = array[index];
}
return newArray;
}
The call would look like this:
int a[] = { 1, 2, 3, 4 };
int *ptr = foo( 4, a );
It takes two lines, but it at least is easier than initializing line by line.
//initialize the array
int array[] = {3,4,2,6};
// initialize a pointer to that array
int *pointer = array;
As others have pointed out, you can initialize non heap arrays, e.g.:
static const int ar1[4] = { ... };
static const int ar2[4] = { ... };
Then initialize your dynamically allocated array from the static data:
void func()
{
int *pointer = new int[4];
...
memcpy(pointer, ar1, sizeof(ar1));
...
memcpy(pointer, ar2, sizeof(ar2));
...
You can do something like this with a standard container and boost::assign.
std::vector vect = list_of(3)(4)(2)(6);
...
vect = list_of(2)(7)(3)(8);