I am attempting to create a two dimensional array depending on the users desired number of rows and columns. I am receiving an error of "use of undeclared identifier 'rows'". I googled and searched on stack overflow but was not able to find a scenario like this, I would like to know what am I doing wrong below is my code :
#include <iostream>
using namespace std;
class Matrix{
public:
int matrixDimensions[rows][columns];
void setMatrix(int x, int y){
rows = x;
columns = y;
}
int getMatrixDimensions(){
return rows;
return columns;
}
private:
int rows;
int columns;
};
int main(int argc, const char * argv[]) {
int a;
int b;
Matrix matrixObject;
cout << "Please enter the number of rows: " << endl;
cin >> a;
cout << "Please enter the number of columns: "<< endl;
cin >> b;
matrixObject.setMatrix(a, b);
cout << "The number of rows and columns are : " << matrixObject.getMatrixDimensions();
return 0;
}
Thank you all feedback is welcomed.I cannot use vectors, thank you for mentioning them but it is not an option here.
In C++, if you want to declare an array regardless of dimension, you can only declare it before the compile time.
For example, let SIZE be the user input during run time
int arr[5] // OK
int arr[SIZE] // NOT OK
If you want to dynamically allocated the array size during the run time, you have to use the pointer.
int* arr = new int [5] // OK
int* arr = new int [SIZE] // OK
Take a look in
How do I declare a 2d array in C++ using new?
Try declaring the variables rows and columns before the functions. C++ will check the syntax line by line. So it might be the issue.
Related
I am a beginner and I would like to ask you something.
We have an array whose size depends on value input by user in a variable ‘arraysize’. Look at below code and comments please, is it a correct way to achieve this said be behaviour?
int * myArray = NULL;
int arraySize;
cout << "Enter array size: ";
cin >> arraySize;
myArray = new int[arraySize];
delete [] myArray;
The earlier answer was a community wiki. Since you asked for an example, here's a more detailed answer.
A std::vector is a class belonging to the standard template library read in detail.
//since you used "using namespace std;" I'm omitting the "std::"
Declaration
vector< int > v; //creates a vector of integers
vector< double > vd; //vector of double values
This is quite similar to int a[/*any number*/].
Inserting values
v.push_back(5); //adds 5 to the end of the vector (or array of variable size)
With the above two lines you dont need to know in advance how many numbers you'll have to store.
One more sample code.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
This program reads values and saves to myvector till 0 is entered in input.
Iteration
std::vector<int>::size_type sz = myvector.size(); //even int works here
// assign some values:
for (unsigned int i=0; i<sz; i++) myvector[i]=i;
Deletion
v.pop_back(); //removes last element
Use std::vector as a C++ best practice.
This code is written in C++ to make a multi dimensional array but it gives an initializing error. The size of array should be given by input console by the user and so it is not constant value. What is the problem and what is the solution? Thanks a lot.
#include <iostream>
using namespace std;
int main()
{
int A , B ;
cout << "A: " << endl;
cin >> A ;
cout << "B: " << endl;
cin >> B ;
int data[A][B] = {{0}};
return 0;
}
The size of array should be given by input console by the user and so it is not constant value.
This is not possible in C++. A suitable replacement for using arrays is using std::vector. You can use:
int A = 10, B = 4;
std::vector<std::vector<int>> data(A, std::vector<int>(B, 0));
If you are using a pre-C++11 compiler, you'll need to have a space between the two >>.
std::vector<std::vector<int> > data(A, std::vector<int>(B, 0));
I am writing a program that asks the user to type in a very large int (much larger than the type int can handle). When receive this int from the user, it is stored in a string. Then, I want to convert this string into an int array (I am using a dynamic int array). After compiling and running the program, I get values that don't make sense. The values of my int array seem to be random gibberish. I don't see why this is so - it doesn't look like my loops are out of bound in the converting process. Please help. The purpose of creating an int array is to then come up with ways to add, subtract, multiply, and compare very large int values. To make it clear what I am intending to do: say the user types in "12345". I want to store this string value into an int array that would have a length of 5, each element corresponding to the next number in the int.
largeIntegers.h
#ifndef H_largeIntegers
#define H_largeIntegers
#include <iostream>
#include <string>
class largeIntegers
{
private:
void readInteger();
// reads integer
public:
std::string s_integer;
int* integer;
int length;
largeIntegers();
// default constructor
void outputInteger();
// outputs integer
};
#endif
largeIntegers.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
largeIntegers::largeIntegers()
{
readInteger();
}
void largeIntegers::readInteger()
{
int i = 0,j = 0, k;
cout << "Enter large integer: ";
cin >> s_integer;
for (; s_integer[i] != '\0'; i++);
length = i;
int* integer = new int[i];
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = s_integer[k++] - 48;
}
void largeIntegers::outputInteger()
{
for (int i = length - 1; i >= 0; i--)
cout << integer[i];
}
User.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
int main()
{
largeIntegers a;
cout << a.length << endl << endl;
cout << a.integer[0] << endl << a.integer[1] << endl;
a.outputInteger();
cout << endl << endl;
return 0;
}
I intentionally made the variables in the header public for debugging purposes. My output on the console after compiling is:
Enter large integer: 111
3
952402760
1096565083
10966961571096565083952402760
This is the problem
int* integer = new int[i];
change to
integer = new int[i];
Your version declares a local variable that just happens to have the same name as your class variable. Easy mistake to make.
also, using standards facilities like std::vector and std::getline would make your code much cleaner in addition to avoid the problem you had, and resolve memory leaks you have now if you call readInterger twice:
void largeIntegers::readInteger()
{
cout << "Enter large integer: ";
std::getline(std::cin, s_integer);
integer = std::vector(s_integer.size());
//your last loop to fill the array probably can be replaced by std::transform
}
I saw an older post on here asking how to do relatively the same thing, but their approach was different and i'm interested to know the hole in my program.
I am attempting to write a program that accepts characters into a 10 character length array. I want the program to evaluate the first array position and delete any duplicates it finds later in the array by identifying a duplicate and moving all of the values to the right of it to the left by one. The 'size' of the array is then decreased by one.
I believe the logic I used for the delete function is correct but the program only prints an 'a' for the first value and the fourth value in the array.
Any help would be greatly appreciated, here is my code:
#include <iostream>
using namespace std;
int letter_entry_print(int size, char array[10]);
int delete_repeats(int& size, char array[10]);
int final_array_print(int size, char array[10]);
int main()
{
char array[10];
int size = 10;
letter_entry_print(size,array);
delete_repeats(size,array);
final_array_print(size,array);
cout<<"\n";
system("pause");
}
int letter_entry_print(int size, char array[10])
{
int i;
for (i=0;i<size;i++)
{
cout << "Enter letter #" << i+1 << endl;
cin >> array[i];
cout << "\n";
}
cout << "\nYour array index is as follows:\n\n";
for (i=0;i<size;i++)
{
cout << array[i];
cout << " ";
}
cout <<"\n\n";
return 0;
}
int delete_repeats(int& size, char array[10])
{
int ans;
int loc;
int search;
int replace;
char target='a';
cout << "Enter 1 to delete repeats.\n\n";
cin >> ans;
if(ans==1)
{
for(loc=0;loc<size;loc++)
{
array[loc]=target;
for(search=1;search<(size-loc);search++)
{
if(target=array[loc+search])
{
for(replace=0;replace<(size-(loc+search));replace++)
{
array[loc+search+replace]=array[loc+search+replace+1];
array[size-1]=0;
size=(size-1);
}
}
}
}
}else(cout<<"\nWhy didn't you press 1?\n\n");
return 0;
}
int final_array_print(int size, char array[10])
{
cout<<"\nYour new index is as follows:\n\n";
int i;
for(i=0;i<size;i++)
{
cout<<array[i];
cout<<" ";
}
cout<<"\n";
return 0;
}
Ok, there are a few things about your code that look odd.
1) you repeat 10 all over the place to the point where there's no way you could resonably change it, but you also pass size along. Instead of making all your functions take arrays of 10 chars, consider just passing in a pointer to char, like:
int final_array_print(int size, char *array)
then you can change the size of your arrays more easily. There's no point in passing size everywhere if you're going to limit yourself forever to 10 items, and there's no good reason to pass arrays of 10 items around if you provide a size!
2) ok, so now you want to look for duplicates. Why do you overwrite the first element in your array with an 'a'?
char target='a';
...
array[loc]=target;
wouldn't you want to do it the other way around?
3) next, as #Mahesh points out, you probably want to use the comparison operator '==' rather than the assignment operator = when looking for duplicates that is:
if(target=array[loc+search])
should probably be
if(target == array[loc+search])
4) Next, dontbeafraidtousealittlewhitespacebetweenyourwordsandpunctuation.Itmakesitaloteasiertoidentifytypingmistakesandspellingerrors.
5) your loop to actually perform the replacement has incredibly complicated indices. It would be easier if you didn't start with replace = 0, but just start at replace = search + 1, try it out and perhaps you'll how much simpler all the rest of the indices become.
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;
}