C++ Dynamic ND Arrays - c++

I have a problem creating ND arrays dynamically.
So for example:
int **A = 0;
A = new int *[rowsA];
for (int i=0;i<rowsA;i++) {
A[i] = new int[columnsA];
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
And passed to a function like: print_matrix(&A[0][0],rowsA,columnsA);
void print_matrix(int *A, int x, int y) {
for (int i=0;i<x;i++) {
for (int j=0;j<y;j++) {
cout << A[i+j*x] << " ";
}
cout << ",";
}
}
For example:
input : 1,2,3,4,5,6,7,8,9
output: 6-digitnumber 6-digitnumber 4,2 6-digitnumber 5,3 6-digitnumber 6
any ideas?

If by a ND array you mean an Iliffe vector, you aren't building it correctly. The data has to be allocated consecutively and thus in one allocation as the memory returned by successive calls to new isn't necessarily consecutive. This should do the work:
int **A = new int *[rowsA];
int *data = new int[rowsA*columnsA];
for (int i=0;i<rowsA;i++) {
A[i] = data + i*columnsA;
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}

Your A variable is an array of pointers (and each pointer points to a sequence of int's) - print_matrix expects a pointer directly to a sequence of int's. The two types are not compatible.
You'll need to either make print_matrix take an int **, or change the use of your A variable to be A[i+j*x] rather than A[i][j]

Related

Array values output incorrectly

I am having a very simple function to input values. But I am getting a wired output. I get different values to what I am inserting? What am I doing wrong?
#include <iostream>
using namespace std;
void testFunc(float arr[], int sizeOfArray);
int main() {
int sizeOfArray = 4;
float arrA[] = {};
float arrB[] = {};
cout << "1st array VALUES" << endl;
testFunc(arrA, 4);
cout << "A -> ";
for(int i=0; i<sizeOfArray; i++){
cout << arrA[i] << " | ";
}
cout << endl;
cout << "2nd array VALUES" << endl;
testFunc(arrB, 4);
cout << endl << "B -> ";
for(int i=0; i<sizeOfArray; i++){
cout << arrB[i] << " | ";
}
cout << endl;
return 0;
}
void testFunc(float arr[], int sizeOfArray) {
for(int i=0; i<sizeOfArray; i++){
cout << "Insert val " << i+1 << ": ";
cin >> arr[i];
}
}
The float arrA[] = {} creates an array of floats with 0 size. When you iterate over it, you access an out of bound memory in here:
for(int i=0; i<sizeOfArray; i++);
You can list initialize an array and not specify the size of an array, using braces {...}. But in such case, the size is deduced from the elements in the list. You have empty list.
For example:
float arr[] = {}; // Empty
float arr[4]; // Four elements, all default initialized
float arr[] = {3.14, 1.61}; // Two elements, specified values
float arr[4] = {3.14, 1.61}; // Four elements, last two are value initialized
You will benefit from taking a look at these articles:
Why aren't variable-length arrays part of the C++ standard?
C++ Containers Library

Filling Dynamically Allocated Array in C++

I am trying to fill up the multi-dimensional array using dynamic memory allocation and running into problem of how to determine the size of each array.
The sizes are also dynamically generated in the for loop, not sure how i can transport this knowledge into looping construct to tell the compiler when to stop.
Please dont answer the problem directly, just a direction needed so i can figure out on how to solve the problem of determining this,
for (int v = 0; v < sizeof(a[y]); v++)
int** a = new int*[n];
for (int i = 0; i < n; i++) {
int colcount;
cout << "Enter Size of Array for " << i << " : ";
cin >> colcount;
a[i] = new int[colcount];
}
// How to fill the matrix now
for (int y = 0; y < n; y++) {
for (int v = 0; v < sizeof(a[y]); v++) {
cout << "Enter Array Content [" << y << "][" << v << "] :";
cin >> a[y][v];
}
}
Update:
Got it working by bringing the for loop inside.
int** a = new int*[n];
for (int i = 0; i < n; i++) {
int colcount;
cout << "Enter Size of Array for " << i << " : ";
cin >> colcount;
a[i] = new int[colcount];
for (int v = 0; v < colcount; v++) {
cout << "Enter Array Content [" << i << "][" << v << "] :";
cin >> a[i][v];
}
}
Last Update:
To better track contents and privileges of template class, i ended up using vectors and with the help of community, here is how i came up.
int n;
cout << "Enter Num of Vectors: ";
cin >> n;
vector<vector <int> > mult_arr(n);
for (int i = 0; i < n; i++) {
int k;
cout << "Enter size for vec " << i << ":";
cin >> k;
mult_arr[i].resize(k);
for (int x = 0; x < k; x++) {
cout << "Enter Array Contents [" << i << "][" << x << "] :";
cin >> mult_arr[i][x];
}
}
You cannot know or find the size of a dynamic allocated array without actually holding the size in a variable. You can not use the classic sizeof(arr)/sizeof(type) to find the size because the sizeof() a pointer is just its type size and not the total array size. Use std::vector or keep tracking the sizes of each dynamic array.
Instead of using pointers to pointers to int, consider using a single allocation. It is easier and faster!
int * matrix = new int[width * height];
matrix[y * width + x] = 0;
delete [] matrix;
I took the liberty to rewrite your program to a more domatic C++ program (including a main function, so you can test it). Technically, this does solve the same problem, but instead of using new and delete, it uses std::vector, which should always be the first thing you should reach for.
Unless you have a very very good reason not to use vector, I advice you forget about new/delete. Know that it's there and get on with your life.
I realize this doesn't actually answer your question. I think it's too long for a comment so I'm providing it as answer instead.
#include <iostream>
#include <vector>
#include <string>
int get_an_integer(std::string message)
{
std::cout << message;
int n;
std::cin >> n;
return n;
}
int main()
{
std::vector<std::vector<int>> matrix;
matrix.resize(get_an_integer("Number of vectors:"));
for (auto& vector : matrix)
{
vector.resize(get_an_integer("Vector size:"));
for (auto& element : vector)
element = get_an_integer("Element value:");
}
for (auto v : matrix)
{
for (auto e : v)
std::cout << e << " ";
std::cout << '\n';
}
}
Notice how I don't have to keep track of anything and I don't really care about the explicit size of anything. Even the values of the elements aren't interesting.
I hope this helps you. If you have any questions, please ask.
You can memset to initialize an array. like
int *arr = new int[5];
fill(c, c + 5, 3); //fill(array, array+size, intialvalue)
cout<<c[4];
I hope this will help you.

Lesser number of columns of the second row "cuts off" a bigger number of columns of the first row

*Edit: Still, when input 3 columns for the 1st row and 2 columns for the 2th, in the output 1st row becomes 2-elemented as the first.
Problem with outputting dynamically allocated number of equipes with separately dynamically allocated number of columns (for number of catches for the each equip)... Namely, if I try to allocate 2 equipes and then for the first equip two "catches" of fish (two columns) and for second equip three catches of fish, everything is o.k.... but if I try input of smaller number of columns ("catches") for the second row (equip) then in the output the "excess" of the first row is "cutted off", so for example if there where a 3 columns input for the 1st row and 2 columns input for the second row, in the output there will be just two columns (indices of numbers) for the every of the two rows.
#include<iostream>
int main()
{
using namespace std;
int *sum;
int *a = new int;
int *b = new int;
cout << "Total number of equips: ";
cin >> *a;
// Allocate a two-dimensional 3x2 array of ints
int** ippArray = new int*[*a];
for (int i = 0; i < *a+1; ++i) {
ippArray[i] = new int[*b];
}
// fill the array
for (int i = 1; i < *a+1; ++i) {
cout << "Total number of catches for " << i << "th equip : ";
cin >> *b;
cout << "Equip number: " << i << endl;
for (int j = 1; j < *b+1; ++j) {
cout << "Catch number: " << j << endl;
cin >> ippArray[i][j];
ippArray[i][j];
}
}
// Output the array
for (int i = 1; i < *a+1; ++i) {
for (int j = 1; j < *b+1; ++j) {
cout << ippArray[i][j] << " ";
*sum = *sum + ippArray[i][j];
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << *sum-3;
// Deallocate
for (int i = 1; i < *a+1; ++i) {
delete [] ippArray[i];
}
delete [] ippArray;
// Keep the window open
cin.get();
return 0;
}
First, don't make your integers into pointers (int *a = new int;) unless they really need to be. It makes the code much harder to read, and if anyone has to maintain your code they'll call you an a-hole.
Second, int** ippArray = new int*[*a]; combined with multiple spots where you do this... for (int i = 1; i < *a+1; ++i) are bad. ippArray has valid references from 0 to *a, therefore it should be for (int i = 0; i < *a; ++i)
Edit: Try something like this http://ideone.com/4egQl3
Edit2: Also the standard advice...
{
std::vector<string> advice;
advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!
Parts of your program that have undefined behaviour
Use of *b before you assign to it
Access out-of-bounds elements of all your arrays
Never initialise sum
Use of *sum before you assign to it
cleaned up, your code becomes
int main()
{
using namespace std;
int sum, a, b;
cout << "Total number of equips: ";
cin >> a;
typedef vector<vector<int> > vvint;
typedef vector<int> vint;
// Allocate a two-dimensional structure of ints
vvint ippArray(a);
// fill the array
for (vvint::size_t i = 0; i < a; ++i) {
cout << "Total number of catches for " << i+1 << "th equip : ";
cin >> b;
cout << "Equip number: " << i+1 << endl;
ippArray[i] = vint(b);
for (int j = 0; j < b; ++j) {
cout << "Catch number: " << j+1 << endl;
cin >> ippArray[i][j];
}
}
// Output the array
for (const vint & inner : ippArray) {
for (int num : inner) {
cout << num << " ";
sum += num;
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << sum;
cin.get();
return 0;
}

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.

C++: Dynamically create array named after for loop iterator

Hey so I want to create n arrays (based off user input) of size x (also off user input). The way I was thinking of doing it was having a for loop perform n iterations and inside the loop ask the user for x. The problem is I'm not sure how to name the array using the variable n, I was thinking something like:
cout << "Enter n: ";
cin >> n
for (i = 0; i < n; i++)
{
cout << "Enter x: ";
cin >> x;
double*array+i;
array+i = new double[x]
}
To sum up my question is: can you create/name an array using a variable in C++?
Unfortunately, you can't do this in C++. Try something like this...
std::cout << "Enter n: ";
std::cin >> n
std::vector<std::vector<double> > arrays(n);
for (std::size_t i = 0; i < n; i++)
{
std::cout << "Enter x: ";
std::cin >> x;
arrays[i].reserve(x);
}
reserve only allocates, but does not construct the objects in the std::vector; if you want to construct them too, use resize.
PS Never use using namespace std; it makes your code harder to read and debug.
Since you are programming in C++, you should use STL containers (especially std::vector) instead of C-style arrays.
If you need to access an array by using the string that has been created in runtime, then you could use std::map< std::string, std::vector<double> >, which is pretty crazy idea though:
typedef std::vector<double> MyVector;
std::map<std::string, MyVector> myVectors;
// create an array:
std::string arrayName;
arrayName = std::string("someArray"); // could be: std::cin >> arrayName;
myVectors[arrayName] = MyVector(10, 1.23); // new vector of size 10
std::cout << myVectors["someArray"][4]; // prints 1.23
I'm not sure what exactly is what you are trying to achieve, but there are most likely more appropriate solutions. Is it really necessary to access these arrays via their names? I'm pretty sure that common std::vector< std::vector<double> > would suffice here.
Here's 3 solutions: the first is closest to your example code, the second is an improvement in order to be able to correctly retrieve the array elements within bounds, and the third is the reason why you are better served with vectors.
Solution 1:
It looks like you want your arrays to have names that are distinguishable by your loop iterator. Like Joe said, you could have an array of an array, so the inner arrays will be named array[0], array[1], ..., array[n - 1]. This will be achieved by using a pointer to pointer to double. Each of the inner pointers will be used to dynamically allocate arrays of double. Don't forget to delete the dynamically allocated memory.
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Enter number of arrays: ";
std::cin >> n;
double** array = new double*[n];
for (int i = 0; i < n; ++i)
{
unsigned int size;
std::cout << "Enter size of array " << i << ": ";
std::cin >> size;
array[i] = new double[size];
for (int j = 0; j < size; ++j)
{
int element;
std::cout << "Enter element " << j << " of array " << i << ": ";
std::cin >> element;
array[i][j] = element;
}
}
for (int i = 0; i < n; ++i)
{
delete [] array[i];
}
delete[] array;
return 0;
}
Solution 2:
However, with the above code, you will have trouble accessing the elements of each inner array. Unless you memorized the size of each inner array you create with this, you might access something out of bounds. Therefore, an update to this code would be to add yet another array, let's call it sizeOfInnerArrays, where each of its element i keeps track of the size of inner array array[i]. Here's the update:
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Enter number of arrays: ";
std::cin >> n;
double** array = new double*[n];
unsigned int* sizeOfInnerArrays = new unsigned int[n];
for (int i = 0; i < n; ++i)
{
std::cout << "Enter size of array " << i << ": ";
std::cin >> sizeOfInnerArrays[i];
array[i] = new double[sizeOfInnerArrays[i]];
for (int j = 0; j < sizeOfInnerArrays[i]; ++j)
{
int element;
std::cout << "Enter element " << j << " of array " << i << ": ";
std::cin >> element;
array[i][j] = element;
}
}
//prints out each array as curly-brace enclosed sets of doubles
for (int i = 0; i < n; ++i)
{
std::cout << "{";
for (int j = 0; j < sizeOfInnerArrays[i] - 1; ++j)
{
std::cout << array[i][j] << ", ";
}
std::cout << array[i][sizeOfInnerArrays[i] - 1] << "}" << std::endl;
}
// free dynamically allocated memory
for (int i = 0; i < n; ++i)
{
delete [] array[i];
}
delete[] array;
delete[] sizeOfInnerArrays;
return 0;
}
Solution 3:
However, that is too complicated, so you are better off using a container, like vector, as Joe suggested, whose data member keeps track of its size.
#include <iostream>
#include <vector>
int main()
{
unsigned int n;
std::cout << "Enter number of vectors: ";
std::cin >> n;
std::vector<std::vector<double> > myVec;
// ^ space between closing angle brackets not needed
// if using C++11 conforming compiler
for (int i = 0; i < n; ++i)
{
unsigned int size;
std::cout << "Enter size of vector " << i << ": ";
std::cin >> size;
std::vector<double> temp;
temp.reserve(size);
for (int j = 0; j < size; ++j)
{
double value;
std::cout << "Enter next value of vector " << i << ": ";
std::cin >> value;
temp.push_back(value);
}
myVec.push_back(temp);
}
for (int i = 0; i < myVec.size(); ++i)
{
std::cout << "{";
for (int j = 0; j < myVec.at(i).size() - 1; ++j)
{
std::cout << myVec.at(i).at(j) << ", ";
}
std::cout << myVec.at(i).back() << "}" << std::endl;
}
return 0;
}