Double dimensional array to single dimensional array - c++

I am just doing an experiment to put values in double dimensional array to a single dimensional array. Below is my code and result:
#include <iostream>
using namespace std;
int main()
{
int p[1][1];
int arrayA[4];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
{
p[i][j] = i+j;
}
}
int *a = &(p[0][0]);
for(int k=0;k<4;k++)
{
arrayA[k] = *a;
cout << "*a: " << *a << endl ;
cout << "array[k] :" << arrayA[k] << endl;
cout << "a: " << a << endl;
cout << "---------------------------" << endl;
a++;
}
system("PAUSE");
}
and the result is:
But I have no idea why it missed the value of p1[0], which value should be 1. But instead, I got a weird number where it is from. Because this is weird to me that I can put the last number in the double dimensional array to the single dimensional array but not the number before.
So I hope somebody can tell me what happen to me code or my method of thinking. Thank you.

This results in an out of bounds on array p:
int p[1][1];
int arrayA[4];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++)
{
p[i][j] = i+j;
}
}
Indexes on arrays run from 0 to N - 1, where N is the size of the array.

The problem is that you wrote:
int p[1][1];
Remember that in C, and in C++, the number on elements for dimensions is the true number that you mean the vector or matrix to have. However, their indexes run from 0 to n-1 (where n is the number you wrote). So your declaration of p should be:
int p[2][2];
instead.
Hope this helps.

You wrote int p[1][1] but I think you meant int p[2][2].

Related

Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers
#include <iostream>
using namespace std;
int main(){
int a,b,i;
int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
}
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.
Moreover, int numbers[]={i}; is undefined, because i has not been initialized.
Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)
If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:
#include <iostream>
int main(){
int a,b;
cin >> a >> b;
unsigned counter = 0;
for (int i=a; i<=b; i++) {
if (i%9==0){
++counter;
}
}
std::cout << counter;
}
i want to use array for my learning porpuses please help me
You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:
#include <iostream>
#include <vector>
int main(){
int a,b;
std::vector<int> by9divisables;
std::cin >> a >> b;
for (int i=a; i<=b; i++) {
if (i%9==0) {
by9divisables.push_back(i);
}
}
std::cout << by9divisables.size();
}
However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.
This declaration
int numbers[]={i};
declares an array with only one element and initializes it with an indeterminate value stored in the variable i because the variable i was not initialized.
The body of this if statement
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
does not make a sense because it always outputs the number of elements in the array numbers that has only one element. But according to the description of the assignment you have to place numbers divisible by 9 into the array.
As the user can enter arbitrary values for the variables a and b then it means that you need a variable length array. However variable length arrays is not a standard C++ feature. Instead you should use the standard container std::vector.
The program can look the following way
#include <iostream>
#include <vector>
#include <utility>
int main()
{
int a = 0, b = 0;
std::vector<int> numbers;
const int divisor = 9;
std::cout << "Enter two integer numbers: ";
std::cin >> a >> b;
if ( b < a ) std::swap( a, b );
for ( int i = a; not ( b < i ); ++i )
{
if ( i % divisor == 0 ) numbers.push_back( i );
}
std::cout << "There are " << numbers.size()
<< " numbers divisible by " << divisor
<< " in the range [" << a << ", " << b << "]\n";
if ( numbers.size() != 0 )
{
std::cout << "They are ";
for ( const auto &n : numbers )
{
std::cout << n << ' ';
}
std::cout << '\n';
}
}
Your code is printing one's for each element found because your array only has one element in it!
Print i instead like so:
#include <iostream>
using namespace std;
int main(){
int a,b,i;
//int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
{
if (i%9==0)
{
cout << "i: " << i << endl;
}
}
}

How to solve segmentation fault error C++

I'm writing a program that gets an array of integers and its logical size. When called it creates a new array containing only the positive numbers from the arrays.
Now, in order to do this I need to write a void type function takes the following parameters:
(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePTR)
I'm supposed to use the pointer int** outPosArrPtr to update the base address of the array containing the positive numbers, and the pointer outPosArrSizePtr to update the array's logical size.
now when I run my code on the xcode compiler the logical size gets updated to a very larger number. So, when I tried to run the program using the online gdb compiler I got the error "Segmentation fault."
From reading what Segmentation fault means I learnt that it means that I'm trying to access memory that "does not belong to me" or memory that is not in the call stack or in the heap portion of the program.
I tried to debug my code by seeing if I was referening any null pointers or see if I was referencing any dangling pointers but it seems like the problem is another one.
My code:
#include <iostream>
typedef int* IntArrPtr;
using namespace std;
int main() {
int arrSize;
int *ptrSize;
ptrSize = &arrSize;
cout << "How many integers will this array hold:\n ";
cin >> arrSize;
IntArrPtr a;
a = new int[arrSize];
fillArr(a, arrSize);
getPosNums4(a, arrSize,&a, ptrSize);
cout << "The new size in main is: " << arrSize << endl;
cout <<"The new array with positive integers is:\n";
/*for(int i =0; i<arrSize;i++) // this runs for a large size of arrSize
cout<< a[i] << " ";
cout<<endl; */
return 0;
}
void fillArr(int a[], int size){
cout << "Please enter " << size << " Integers separated by spaces\n";
cout << "Press enter when finished >\n";
int i;
for (i=0;i<size;i++)
cin >> a[i];
}
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr,int* outPosArrSizePtr){
IntArrPtr newArr;
newArr = new int[arrSize];
int i;
int newIndx = 0;
outPosArrSizePtr = &newIndx;//initiliaze the pointer.
for(i=0;i<arrSize;i++){
if(arr[i] > 0){
newArr[newIndx] =arr[i];
newIndx++;
}
}
arrSize = newIndx;
*outPosArrSizePtr = arrSize;
cout << "The new size is of *outPosArrSizeptr is: " << *outPosArrSizePtr << endl;
for(int j=0;j<newIndx;j++)
outPosArrPtr[j] = &newArr[j];
delete []newArr;
newArr = NULL;
for(int i=0;i<newIndx;i++)
arr[i] = *outPosArrPtr[i];
}
an example When I run this program on Xcode:
How many integers will this array hold:
6
Please enter 6 Integers separated by spaces
Press enter when finished >
3 -1 -3 0 6 4
The new size is of *outPosArrSizeptr is: 3
The new array with positive integers is:
The new size in main is: 7445512
The program ended with exit code: 0
There are quite a few problems there, but the most crucial one is that assigning a value to a function's argument has no effect on the variable whose value you passed as the argument.
It doesn't matter that the argument is a pointer – there is nothing special about pointers.
What I think is happening is that your "copy back and forth" loop (I can't understand what it's supposed to do) in the function is writing outside the input array, causing undefined behaviour and, in this case, overwriting variables in main.
You're overcomplicating your function quite a bit. It should
Create a new array
Copy the positive values to this array
Update the output parameters with the address of this array and its (logical) size
(Think of out parameters as return values and handle them last.)
Something like this:
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr,int* outPosArrSizePtr){
int* newArr = new int[arrSize];
int newIndx = 0;
for (int i = 0; i < arrSize; i++){
if (arr[i] > 0){
newArr[newIndx] = arr[i];
newIndx++;
}
}
*outPosArrPtr = newArr;
*outPosArrSizePtr = newIndx;
}
You should also not pass pointers to your "originals" for this function to modify, you should use new variables.
int main() {
int arrSize = 0;
cout << "How many integers will this array hold:\n ";
cin >> arrSize;
int* a = new int[arrSize];
fillArr(a, arrSize);
int * positives = nullptr;
int positiveSize = 0;
getPosNums4(a, arrSize, &positives, &positiveSize);
cout << "The new size in main is: " << positiveSize << endl;
delete [] a;
delete [] positives;
}
Modern C++ uses vector rather than manually allocating arrays. Manual allocation is prone to a variety of errors that are very difficult to debug.
The logic in your getPosNums4 method appears to be the trouble. If I understand the requirement, it should look for positive integers in the input array and copy them to a newly allocated output array. Over-allocating the output array is non-optimal but not an actual bug.
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr,int* outPosArrSizePtr){
IntArrPtr newArr;
newArr = new int[arrSize];
int i;
int newIndx = 0;
for(i=0;i<arrSize;i++){
if(arr[i] > 0){
newArr[newIndx] =arr[i];
newIndx++;
}
}
*outPosArrSizePtr = newIndx;
cout << "The new size is of *outPosArrSizeptr is: " << *outPosArrSizePtr << endl;
*outPosArrPtr = newArr;
}
Note the the newly allocated array will need to be delete[] by the calling function or a memory leak will result.
Here is the same program in modern C++. Note that there is no use of new/delete which saves a lot of misery.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> integer_vector;
vector<int> positive_vector;
cout << "Type in integers. Type a Q to continue:" << endl;
int an_int;
while(cin >> an_int)
integer_vector.push_back(an_int);
for_each(integer_vector.begin(),integer_vector.end(),[&](int const& n){
if(n > 0)
positive_vector.push_back(n);
});
cout <<"The new array with positive integers is:\n";
for(auto const & element:positive_vector)
cout<< element << " ";
cout<<endl;
return 0;
}

hardcoding 2D array values

Trying to insert values into a 2D array, but the output isnt giving my values, instead random letters
int myArr[8][2] = {700,730,760,790,810,840,910,1000}{0.011,0.035,0.105,0.343,0.789,2.17,20,145};
cout << myArr << endl;
system("Pause");
How should I adjust the code, or is it easier to use a text file and insert?
Numerous problems:
the array dimensions are wrong
you don't have outer braces or a comma for the nested arrays
you're trying to store double precision floating point values in an int array
you can't use cout with an entire array.
The array declaration should probably be something like this:
double myArr[2][8] = { {700,730,760,790,810,840,910,1000},
{0.011,0.035,0.105,0.343,0.789,2.17,20,145} };
and to output the contents you could do something like this:
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 8; ++j)
{
cout << " " << myArr[i][j];
}
cout << endl;
}
Live Demo
First - you can't print the whole array just by using cout << myArr, you need to iterate over the elements of the array using a for loop.
Second - you are trying to put decimal values into an integer array which will truncate all of the decimals.
Third - Your array should be sized myArr[8][2] not myArr[2][8]. I'm surprised your compiler lets you get away with this. You should probably look into using a different compiler.
You need to iterate through each row and column, otherwise you're just printing out the pointer value of the array handle.
for (int i=0;i<8;i++){
for (int j=0;j<2;j++){
cout << myArr[i][j] << " ";
}
cout << endl;
}
system("Pause");

Segmentation fault on creating matrices

I was practicing on c++ on some tutorials and I encountered on a tutorial that creates matrices, I wanted something more from it and I modified it, I dont know matrices at all cuz I didnt learn them yet at school but this code below sometimes works sometimes not.
When it doesn't work I usually get: Segmentation fault.
why does this happen ?
before it happened everytime but after i gave a 0 value to variable line and member on the beginning it doesnt happen anymore, but still if I type exc
Line: 10
Member: 9
it gives:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 1 7 8 9
Segmentation fault
and stopes.
Can anyone explain me this ?
thank you !
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int line=0,member=0;
int i,j,matrice[line][member];
cout << "\nLine: ";
cin >> line;
cout << "Member: ";
cin >> member;
cout << "\nCreated Matrice: \n" << endl;
for (i=0;i<line;i++)
{
for (j=0;j<member;j++)
{
matrice[i][j]=i*j+1;
cout << setw(5) << matrice[i][j];
}
cout << "\n\n";
}
return 0;
}
int line=0,member=0;
int i,j,matrice[line][member];
This line shouldn't compile. In standard C++,
arrays of 0 size are not allowed
array sizes must be constant expressions
It appears that your compiler allows these as extensions. In any case when you later input line and member your array size doesn't change. You should define your array after you've input these numbers. But the array must be dynamically allocated (better yet, use vectors)
#include <vector>
//...
int line, member;
cin >> line >> member;
vector<vector<int> > matrix(line, vector<int>(member));
or if you don't want to use vector for educational purposes, do this:
int line, member;
int ** matrix;
cin >> line >> member;
matrix = new int*[line];
for(int i = 0; i < line; ++i)
matrix[i] = new int[member];
Don't forget to free the matrix.
for(int i = 0; i < line; ++i)
delete [] matrix[i];
delete [] matrix;
I suggest that you should read a good C++ book
HTH
The matrice array is initialized with a size of [0][0], which are the values of line and member. Since you override the values with the inputted values, the bounds used in the for loops are invalid.
i.e. You are accessing items out of the array's bounds.
You may want to use new to dynamically create arrays, or just use std::vector which resizes itself.
Also, it is not standard, but if your compiler supports it, you can use variable-length arrays. They behave like regular arrays but are allocated using a runtime-computed value :
int line=0,member=0;
int i,j;
cout << "\nLine: ";
cin >> line;
cout << "Member: ";
cin >> member;
int matrice[line][member];
You should also check for the inputted values, since C++ does not allows zero-size arrays (And it wouldn't make sense in your program anyway.)
You are using dynamic array without allocating memory using malloc or similar. That is in your line int i,j,matrice[line][member]; is not an array with constant size thus memory should be dynamically allocated. Or use a constant matix size as poster above suggested.
I agree with other comments that using vectors is a much safer way to solve your problem: using arrays directly is definitely error-prone. Of course, if your exercise requires using arrays, then you should use arrays.
Regarding the performance, I have written a small test using g++ on Ubuntu 10.04. Running
g++ --version
I get
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
My test program creates a 100x100 matrix and sets each element to some value. It first has a few declarations:
#include <vector>
#include <iostream>
#include "util.h" // Timer utilities.
#define LINE_COUNT (100) // The number of lines.
#define COL_COUNT (100) // The number of columns.
#define REPETITIONS (100000) // Number of repetitions for each test.
using namespace std;
Then I have the test using vectors:
void use_vectors()
{
int line = LINE_COUNT;
int member = COL_COUNT;
vector<vector<int> > matrix(line, vector<int>(member));
// Set data.
for (int i = 0; i < line; i++)
{
for (int j = 0; j < member; j++)
{
matrix[i][j] = -5;
}
}
}
Then I have a function to perform the same test (create matrix and set values) using arrays:
void use_arrays()
{
int line = LINE_COUNT;
int member = COL_COUNT;
int **matrix;
matrix = new int * [line];
for (int i = 0; i < line; i++)
{
matrix[i] = new int[member];
}
// Set data.
for (int i = 0; i < line; i++)
{
for (int j = 0; j < member; j++)
{
matrix[i][j] = -5;
}
}
for (int i = 0; i < line; ++i)
{
delete [] matrix[i];
}
delete [] matrix;
}
The main program repeats both tests, and records the time needed for each of them. Here is the main program:
main()
{
long int es = 0;
long int eu = 0;
start_timer();
for (int i = 0; i < REPETITIONS; i++)
{
use_vectors();
}
stop_timer();
es = elapsed_sec();
eu = elapsed_usec();
cout << "Vectors needed: " << es << " sec, " << eu << " usec" << endl;
start_timer();
for (int i = 0; i < REPETITIONS; i++)
{
use_arrays();
}
stop_timer();
es = elapsed_sec();
eu = elapsed_usec();
cout << "Arrays needed: " << es << " sec, " << eu << " usec" << endl;
}
The timer functions are based on the library function gettimeofday() (see e.g. http://linux.die.net/man/2/gettimeofday).
The result is the following:
Vectors needed: 24 sec, 624416 usec
Arrays needed: 10 sec, 16970 usec
So it seems that vectors do have some overhead wrt to arrays. Or can I do something to improve the performance of vectors? I checked my benchmark code a few times and it seems to me I got it right.
Anyway, I would by no means advise using arrays just to gain performance unless it really makes a big difference in your application.
You want to allocate memory dynamically.
Then, Use Dynamic allocation like this:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int line=0,member=0;
int i,j;
int **matrice; //Define matrice as a 2D array(a Matrix)
cout << "\nLine: ";
cin >> line;
cout << "Member: ";
cin >> member;
//start of dynamic allocation
matrice=new int*[line];
for (i=0;i<line;i++)
matrice[i]=new int[member];
//End of dynamic allocation
cout << "\nCreated Matrice: \n" << endl;
for (i=0;i<line;i++)
{
for (j=0;j<member;j++)
{
matrice[i][j]=i*j+1;
cout << setw(5) << matrice[i][j];
}
cout << "\n\n";
}
delete[] matrice; //Releasing allocated memory
return 0;
}

How do I fix the size of my array?

everyone. I am struggling with understanding why my numbers variable keeps outputting 1. I am trying to double the size anytime the number of elements is equal to the size of the array but I end up not getting anywhere near that part of my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int selection;
int size = 2;
// Initializing the array
int *dArray;
int v = 0;
int i, j, temp;
dArray = new int[size];
dArray[0] = 2;
dArray[1] = 3;
int numbers = sizeof(dArray) / sizeof(dArray[0]);
do {
// Printing the menu
cout << "1) Print Elements" << endl;
cout << "2) Add Element" << endl;
cout << "3) Delete Element" << endl;
cout << "4) Return Size" << endl;
cout << "5) Exit" << endl;
cout << "Enter your selection number: ";
cin >> selection;
switch (selection)
{
case 1:
// Outputting the elements
for (int i = 0; i < size-1; i++)
{
cout << dArray[i] << ", ";
}
cout << dArray[size - 1] <<endl;
cout << numbers << endl;
break;
case 2:
// Asking for another element
cout << "What number shall be put into the array? \n";
cin >> v;
if (numbers== size)
{
// If the size is too small...
int *nArray = new int[2 * size];
for (int i = 0; i < size; ++i)
{
nArray[i] = dArray[i];
}
delete[] dArray;
dArray = nArray;
// Finished creating a new array
cout << "Array size expanded to " << 2 * size << endl;
// Adding the element
dArray[size] = v;
size = 2 * size;
// Sorting the elements
for(i=0;i<numbers;i++)
{
for(j=i+1;j<numbers;j++)
{
if(dArray[i]>dArray[j])
{
temp =dArray[i];
dArray[i]=dArray[j];
dArray[j]=temp;
}
}
}
}
else
{
// Adding the element
dArray[size] = v;
size = 2 * size;
// Sorting the elements
for(i=0;i<numbers;i++)
{
for(j=i+1;j<numbers;j++)
{
if(dArray[i]>dArray[j])
{
temp =dArray[i];
dArray[i]=dArray[j];
dArray[j]=temp;
}
}
}
}
break;
}
} while (selection!= 5);
cin.get();
cin.ignore();
return 0;
}
Does anyone know why the sizeof function keeps acting this way?
This is not the size of your array. It's the size of a pointer, divided by the size of an int.
int numbers = sizeof(dArray) / sizeof(dArray[0]);
This is the size of the array in your program.
int numbers = size;
sizeof(dArray) gives you the size of dArray. dArray is defined as int *dArray, so its size is sizeof(int*). That doesn't change, regardless of what the pointer points to. That's different from an actual array; your size code would work correctly with int dArray[3];.
To get the size of the array, just use your size variable; that's the number of int objects that were allocated.
Even better, use std::vector<int>; its size() member function tells you how many elements it has.
int numbers = sizeof(dArray) / sizeof(dArray[0]);
Numbers is resolving to 1 because dArray is a pointer to the start of your array, not the array itself. When you call sizeof() you are getting the size of the pointer, not the array. On a 32 bit application, the pointer is 32 bits (4 bytes) and your first int is also 32 bits (4 bytes). So what this statement resolves to is
int numbers = 4 / 4;
leaving 1. If you instead declared an array of doubles then sizeof(dArray[0]) would be 8 but the size of the pointer would still be 4, so the statement would resolve to numbers = 4 / 8 = .5, but since numbers is an int it would just resolve to 0. So your code would still break, but in new exciting ways.
Interestingly enough, if you compiled this as a 64 bit application sizeof(dArray) would be 64 bits (8 bytes), so you would get numbers = 8 / 4 = 2 as you expected. Then you would double your array size and your code would break because numbers would resolve to 2 which would potentially be even more confusing, so be thankful you caught it now!
I agree with what others have said though. If you use a Vector you can just keep pushing values onto the end of it and let it worry about changing the size of the array!