Basic Array Error in C++ - c++

I am trying to learn arrays and I can not figure out this code. For some reason when I run this an error is identified, but the entire code is highlighted as the error so I am confused as to where the error really is. I know this is very basic, but any help would be very appreciated.
#include <iostream>
using namespace std;
int main()
{
int x[8];
for (int i =0; i<= 8; i++)
x[i] = i;
return 0;
}

Try
#include <iostream>
using namespace std;
int main()
{
int x[8];
for (int i =0; i<8; i++)
x[i] = i;
return 0;
}
Because arrays start at 0 accessing array index 8 is to far as that is actually slot 9.

Related

No output after new arrays being initialized in C++

I am trying to initialise two 2D arrays, namely psi_0 and omega_0, with the data type as double. The sizes of the arrays are 401x401. I have written the last printing statement to check if the code is running properly or not. As soon as I initialise arrays, the last line doesn't get printed and this is getting displayed only: PS C:\Users\Avii\Desktop> cd "c:\Users\Avii\Desktop\" ; if ($?) { g++ trialc++.cpp -o trialc++ } ; if ($?) { .\trialc++ }.
Following is my code:
#include<iostream>
#include<iomanip>
#include <math.h>
#include <vector>
#include <algorithm>
#include <thread>
#include <chrono>
using namespace std;
void display(vector<double> &v){
for (int i = 0; i < v.size(); i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
int main(){
const int N = 401;
const double pi = 3.141592653589793;
double L = pi/2;
double r = 1.5;
//-------------------------------------------------------------------
.
..
...
double psi_0[N][N];
double omega_0[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
psi_0[i][j] = sin(x_vec[i]) * (sin(y_vec[j]));
omega_0[i][j]= 2 * sin(x_vec[i]) * sin(y_vec[j]);
}
}
cout<< "everything is fine"; // to check if the code has run till last or not!
return 0;
}
Here x_vec and y_vec are two vectors of size 401 and data type as double. I have tried using flush but could not see the problem is solved!
Any help is highly appreciated!!

Printing issue in vectors (CPP) in looping

I was working on a problem statement. For its implementation, I am using vectors.
#include <iostream>
#include <vector>
using namespace std;
int busRemaining(vector<vector<int>> &busStation) {
int answer=0;
for(int i=0; i<=busStation.size(); i++) {
for(int j=i+1; j<=busStation.size(); j++)
{
if((busStation[i][0] <= busStation[j][0]) && (busStation[i][1] >= busStation[j][0])) {
answer++;
}
}
}
return answer;
}
int main()
{
vector<vector<int>> v = {{2, 8},{6, 10},{12, 14},{12, 20}};
cout<<busRemaining(v);
return 0;
}
The issue I am facing is -> after I run the program nothing is printed on the console. I have initialized answer to 0, So I suggest even if my looping logic is wrong it should return 0 at least.
You are using the wrong condition for your for-loops. Vector's are zero-indexed, so you should use less-than instead of less-than-or-equal:
for (int i = 0; i < busStation.size(); i++)
^
|
here
and
for (int j = i + 1; j < busStation.size(); j++)
^
|
here
The reason your function does not return, is because you touch memory outside the vector, memory that might not be allocated by your program, which makes your program's behavior undefined, i.e. the behavior of your program depends on the compiler and the operating system you use.
I could problems in your code, you can not access busStation[busStation.size()] because that element does not exist. Try to fix that issue first.
As you can see, in both for loops you have put i<=busStation.size(); and j<=busStation.size();. It is giving out of range error and causing a runtime error. it should be < and not <=. I hope you know why is it so. And in the 2nd loop, you have used again busStation.size() which might cause an error if you are trying to iterate elements of individual vectors inside vectors. I have written this code just to fix errors. I don't know if it works as you want.
#include <iostream>
#include <vector>
using namespace std;
int busRemaining(vector<vector<int>> &busStation) {
int answer=0;
for(int i=0; i<busStation.size(); i++) {
for(int j=i+1; j<busStation[i].size(); j++)
{
if((busStation[i][0] <= busStation[j][0]) && (busStation[i][1] >= busStation[j][0])) {
answer++;
}
}
}
return answer;
}
int main()
{
vector<vector<int>> v = {{2, 8},{6, 10},{12, 14},{12, 20}};
cout<<busRemaining(v);
return 0;
}

Dynamically allocated 2D Array issue

I am trying to understand what I am doing wrong when attempting to dynamically allocate the 2D array "allWordMultiArray" and assign values to it.
I've been reading a lot of articles online (and in Stackoverflow in particular) and tried to implement it in a lot of ways but unsuccessfully. using C++ 14.
So, the following code creates a warning of "Using uninitialized memory '*allWordMultiArray[i]'".
Obviously, when trying to cout the values in the 2D array it prints garbage.
Can someone point to me what the problem is?
Here's a summary of the code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int letters = 26;
int main() {
....
int numWords, pos;
string input;
int** allWordMultiArray;
cin >> numWords;
allWordMultiArray = new int* [numWords];
for (int i = 0; i < numWords; i++) {
cin >> input;
allWordMultiArray[i] = new int[letters];
for (unsigned long int j = 0; j < input.size(); j++)
{
pos = (input[j] - 'a');
//Here is the problem. Garbage values
allWordMultiArray[i][pos]++;
}
}
return 0;
}
Your help is very much appreciated.
This line:
allWordMultiArray[i] = new int[letters];
does allocate memory for an array, but the values in the array are indeterminate. Reading from these values, like here:
allWordMultiArray[i][pos]++;
will invoke undefined behavior.
Just initialize the array when you allocate it:
allWordMultiArray[i] = new int[letters] {};
// ^^

Segment Fault due to scope of variable

I am a beginner to C++.
I am trying to read in input from the console, so I have the code below:
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
#define maxn 2006
int A[maxn][maxn];
int main() {
memset(A,0,sizeof(A));
int n = 0,m = 0;
cin >> n >> m;
for(int i = 0; i < n; ++i){
string str; cin >> str;
for(int j =0; j < m; ++j)
A[i][j] = str[j]-'0';
}
return 0;
}
A sample input looks like this
5 7
0101010
1000101
0101010
1010101
0101010
My program above works perfectly.
However, for learning purpose, I did nothing but move the declaration of 2D int array A into the main function, which looks like this:
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
#define maxn 2006
int main() {
int A[maxn][maxn];
memset(A,0,sizeof(A));
int n = 0,m = 0;
cin >> n >> m;
for(int i = 0; i < n; ++i){
string str; cin >> str;
for(int j =0; j < m; ++j)
A[i][j] = str[j]-'0';
}
return 0;
}
I rebuild it and run, I get segmentation fault 11.
Anyone know what's going on here? Why does the code break down after the subtle change?
Thanks!
Anyone know what's going on here?
Yes: stack overflow.
By moving the variable you made it a local (stack allocated) instead of global (allocated at startup in the BSS section of the binary).
The size of your variable is 16,096,144 bytes (2006 * 2006 * 4). And stack is usually limited, often to 8MB. On a UNIX system, after ulimit -s unlimited, your modified program may start working again.

Unable to store value in array in c++

What i'm willing to do is i wanna convert all the values of the array to their respective ASCII values and then store them in another array. My code is able to convert the character values into ASCII but it fails in storing them in another array. Please help me out.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
return 0;
}
When I try to run this program I get the following error message:
warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
Thank You!
I got the previous one. But what if i wanna print all those elements stored in ass once again. I'm using the following code and it does nothing. I'm not getting any error.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
for(int q=0; q<size; q++){
cout<<ass[q];
}
return 0;
}
Your warning is not a failure. It's just pointing out that once you store it, you never use it!
Your warning is just telling you that you aren't using the variable ass. It's not an error, but you do have a problem in your code:
int size = sizeof(name);
for (int i = 0; i < size; i++)
{
int p = name[i];
for (int j = 0; j < size; j++)
{
ass[j] = p;
}
}
The second for loop will simply overwrite each character in ass with the single character p. A nested for loop isn't needed, just assign the character from the main loop:
for (int i = 0; i < size; i++)
{
int p = name[i];
ass[i] = p;
}
Moreover, this can be facilitated through the Standard Library functions. For example:
#include <iostream>
#include <string>
int main()
{
std::string ass;
std::string name = "Chaitanya";
for (auto a : name)
{
std::cout << static_cast<int>(a);
}
ass = name;
std::cout << ass; // "Chaitanya"
warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
This warning just say that you have set the variable ass but you never use it. It is not an error at all.
As an example, try to output a value for this array and the warning will disappear:
std::cout << ass[0] << std::endl;
There is a little part on this warning here: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html.
The warning is correct, you only set the values of ass you do not use the values set afterwards. If you added let's say a cout after the loop the warning would go away:
std::cout << ass[0] << std::endl ;
I also, don't think you need the second inner loop, if you want to print out each element of ass you could add it that after you set it. So the fix and additions print out could look like this:
for(int i=0; i<size; i++)
{
int p=name[i];
cout<<p<<"\n";
ass[i]=p;
std::cout << ass[i] << std::endl ;
}