Reverse an Array but i'm getting a segmentation error - c++

What am I doing wrong ???
It is giving me an error of segmentation fault .
I don't know what memory i'm accessing ??
#include <iostream>
using namespace std;
int main() {
int t;
int n;
int arr[n];
cin>>t;
cin>>n;
// taking array elements from user
for(int i=0; i<n;i++)
{
cin>>arr[i];
}
// reverse of the array
for(int i=n-1; i>=0;i--)
{
cout<<arr[i];
}
//code
return 0;
}

int n;
You've default initialised this variable. Thus, the value is indeterminate.
int arr[n];
Here, you use that indeterminate value. Thus, the behaviour of the program is undefined.
There are "data flow" languages where using a variable will stop execution waiting for you to initialise it later and continue. C++ isn't such language. You must initialise everything before using the value.
Besides that, n isn't a compile time constant expression. Because the size of the array variable isn't compile time conastant, the progarm is ill-formed in C++.
If you want an array to have a dynamic size, you can use dynamic storage. Simplest way to create a dynamic array is to use std::vector.

For starters you are trying to declare a variable length array
int n;
int arr[n];
Variable length arrays is not a standard C++ feature. Moreover you are using an uninitialized variable n as the size of the array.
Either declare the array with an expected maximum size or use standard container std::vector<int>. At least you should write provided that the compiler supports variable length arrays
int t;
int n = 1;
cin>>t;
cin>>n;
if ( n < 1 ) n = 1;
int arr[n];
//...
Also you are not reversing an array. You are trying to output an array in the reverse order.
To reverse an array you could use standard algorithm std::reverse or you can write an appropriate loop yourself as for example
for ( int i = 0; i < n / 2; i++ )
{
// or use std::swap( arr[i], arr[n-i-1] );
int tmp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = tmp;
}
and then you can output the reversed array.

You are not allowed to define array with Unknown size in C++ so int arr[n]; is Wrong! and if you have to use arrays and not know the size of it , you should use dynamic array with Pointers like this : int* a = new int[n] and also Deallocate Heap memory with Delete []array_name at end of your program and if it is possible for you not use arrays It's better for you use vectors because the size of it is dynamic.
look at this with vectors :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//by : Salar Ashgi
int main()
{
int k;
cout<<"Enter number of elements ?\n";
cin>>k;
vector<int> v;
cout<<"--------------------\n";
int x;
for(int i=0;i<k;i++)
{
cout<<"Enter num "<<i+1<<" : ";
cin>>x;
v.push_back(x);
}
reverse(v.begin(),v.end());//algorithm.h
cout<<"Reverse : \n";
for(int i=0;i<k;i++)
{
cout<<v[i]<<" ";
}
}

Related

timeout: the monitored command dumped core

i am running this code in online compiler showing dumped core error this program finding highest product of two pair.
#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}
int main()
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
while(t--){
for(int i=0; i<n;i++){
cin>>arr[i];
}
}
maximumproductpair(arr,n);
return 0;
}
in code everything fine then why this error?
Mistake 1
The problem is that your t and n variables are uninitialized. This means both t and n have garbage value. And when you wrote:
int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value
You have undefined behavior because n has garbage value.
This is why it is advised that
always initialize built in types in local/block scope.
Mistake 2
Second, note that in C++ the size of an array must be a compile-time constant. So take for example the following code snippets:
int n = 10;
int array[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int array[n]; //CORRECT
Similarly,
int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression
Also note that some compilers provide compiler extension that lets you have variable length array. You can read more about it at Why aren't variable-length arrays part of the C++ standard?.
If you want to take the size of the array as input from the user then you should use dynamic sized containers like std::vector :
int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int
Also see Why should I not #include <bits/stdc++.h>?.

Reverse of an array Hackerrank

This is a syntax of a program that I made of hackerrank to reverse an array. The location of the question is Practice < Data Structures < Arrays < Arrays - DS
the program seems to work fine on an online compiler but is showing error over hackerrank.
can anyone guide me where I went wrong?
#include<iostream>
using namespace std;
int main(){
int n,i;
int arr[n];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
You are creating an array with n elements before you read n, i.e n is having garbage value. Here is correct working code.
#include <iostream>
using namespace std;
int main(){
int n,i;
cout<<"Enter number of elements"<<endl; // Comment it if you don't want debug console outut
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements"<<endl; // Comment it if you don't want debug console outut
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
I changed your solution and it work fine now , i will tell you some notes for your future:
1 - You have to read size of array first before declare array as mentioned in comments by #HolyBlackCat , otherwise it will give garbage value.
2 - this command int arr[n]; won't work on all Compilers and may give you an Error. Is there a solution to declare array without specific size ? Yes , you can use Vector like that vector<int> arr(n);but you have to include library of vector first #include<vector>
3 - In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. On most operating systems returning 0 is a success status like saying "The program worked fine". So you have to write return 0; in the end of your program.
#include<iostream>
#include<vector> // must include to use Vectors
using namespace std;
int main(){
int n;
cin >> n; // Must read size of array first , otherwise it will give it garbude value
vector<int> arr(n); // instead of int arr[n]
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
for(int i = n-1 ; i >= 0 ; i--)
cout << arr[i] << " ";
cout << endl; // to print new line as mentioned in the problem statement
return 0; // Prefer to use it always
}
Hope that helps you and Good Luck.
The exercise of Hacker Rank needs that you reverse an array of integers, might you have a problem with the variable size array, cause some compilers support this characteristic but others not.
And Hacker Rank do not support some properties in other languages like JS , Hacker Rank do not support prompt() for take an input.
In any case for fix this error you can use vector class.
#include<iostream>
#include<vector>//Include library vector for dynamic size of array
using namespace std;
int main(){
int n;
cin>>n;
vector<int> arr(n);//Declare the vector with a max size n
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i = n-1 ;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
This code has passed al test cases of hackerRank
All the test on hackerRank had passed

Array not working, but shows std::bad_alloc (How to fix this?)

just started studying c++ and i have to make a dynamic array with an function that gets the max array value and prints it. And there seems to be a problem with my code. What have i done wrong, please help (criticism is much appreciated):
#include <iostream>
using namespace std;
int getmax(int* arr,int n)
{
int res=arr[0];
for (int i=0;i<n;i++)
{
if (res<arr[i]) res=arr[i];
}
return res;
}
int main()
{
int*arr;
int n;
arr=new int[n];
cout<<"Enter array length: ";
cin>>n;
for(int i=0; i<n; i++)
{
cout<<"Enter array number "<<i+1<<". : ";
cin>>arr[i];
}
int maxi;
maxi=getmax(arr,n);
cout<<"Biggest number in array is "<<maxi;
delete[]arr;
return 0;
}
The comments already seem to have fixed your problem, but since you asked for (constructive) criticism, you should really study modern C++. In modern C++ we only use bare pointers when there is no other way. We also leverage the standard library whenever it is appropriate to do so. Just these two things will quickly make you a much more powerful programmer and reduce the opportunity for mistakes, provided you study the language and the library.
Here is an example of your program applying these principles:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
size_t n;
cout<<"Enter array length: ";
cin>>n;
vector<int> arr(n); // Create a vector with n integers
// Iterate over the vector
for( auto i = arr.begin(); i != arr.end(); ++i )
{
cout<<"Enter array number "<< (i-arr.begin())+1 << ". : ";
cin>>*i; // Assign the input to the vector element through the iterator
}
// Get an iterator pointing to the largest element in the vector
auto maxi = max_element(arr.cbegin(), arr.cend());
cout<<"Biggest number in array is "<< *maxi << '\n';
return 0;
}
The std::vector constructor allocates the memory, and the destructor frees the memory when arr goes out of scope. No more tedious matching new and delete. When you need to extend the lifetime of an object beyond the current scope use smart pointers or containers that have the lifetime your object needs.

One of the values in a dynamically allocated array always prints a garbage value

Why is p[1].x printing out to a garbage value?
Is it possible to initialize a dynamically allocated array to a given array? If yes, then how?
#include <ioStream>
using namespace std;
struct point{
int x;
int y;
};
int N;
point *p = new point[N];
int main(){
cin>>N;
for(int i=0; i<N; i++){
cin>>p[i].x>>p[i].y;
}
for(int i=0; i<N; i++){
cout<<"("<<p[i].x<<", "<<p[i].y<<")"<<endl;
}
}
On these two lines, you are sizing an array with a variable that is zero initialized (N).
int N;
point *p = new point[N];
Therefore, you would be newing an array of length 0. This would lead to problems once you cin>>N because you use that variable to loop and write to the array, which will be writing outside the allocated space.
These types of cases really beg for std::array or std::vector.
Your code has undefined behaviour because variable N was not initialized with the number of potential elements of the array when it was used to allocate the array in the heap
int N;
point *p = new point[N];
That is as a global variable with the static storage duration it was assigned 0 by the compiler. According to the C++ Standard
When the value of the expression is zero, the allocation function is
called to allocate an array with no elements.
Rewrite your code at least like
#include <ioStream>
using namespace std;
struct point{
int x;
int y;
};
int main(){
int N;
cin>>N;
point *p = new point[N];
for(int i=0; i<N; i++){
cin>>p[i].x>>p[i].y;
}
for(int i=0; i<N; i++){
cout<<"("<<p[i].x<<", "<<p[i].y<<")"<<endl;
}
}
If you know the maximum number of points, better do something like:
const int MAXN = 1000;
Point p[MAXN];
int N;
cin >> N;
// ...
You can manually allocate space as well but you should read N first.
cin >> N;
Point *p = new Point[N];
// ...
A third option is to use a container (vector for dynamic arrays).
vector<Point> p;
cin >> N;
while(N--)
{ int x, y;
cin >> x >> y;
Point p_(x, y); // Assumes constructor exists
p.push_back(p_);
}

array concatenation of two different arrays

im doing simple genetic algorithm uniform crossover operation . for that im using two arrays as parent and mother.i want concatenate the childs for getting the offsprings(childs).
i have problem in adding the arrays .any help plssss.i did it ubuntu
#include<iostream>
#include <fstream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
int P[ ]={3,7,6,5,2,4,1,8};
int N[ ]={8,6,7,2,5,3,4,1};
int r= (sizeof(P)/sizeof(*P)) ;
int s= (sizeof(N)/sizeof(*N));
int val=r/2 ;
int t1[val],t2[val],t3[val],t4[val],n=0,p=0;
for(int m=0;m< val;m++)
{
t1[n]=P[m];
t2[n]=N[m];
n++;
}
for(int x=val;x< r;x++)
{
t3[p]=P[x];
t4[p]=N[x];
n++;
}
int* child=new int [val+val];
copy(t1,t1+val,child);
copy(t3,t3+val,child+val);
cout << child;
}
return 0;
}
This part is wrong:
int t1[val], t2[val], t3[val], t4[val]
You can only use constant values to declare the size of arrays.
You can either use a std::vector or dynamically allocate memory for the t-arrays.
std::vector<int> t1(val);
std::vector<int> t2(val);
for(int m = 0; m < val; m++)
{
t1[n] = P[m];
t2[n] = N[m];
n++;
}
There seem to be multiple errors in your code.
Variable length arrays are at present not supported in C++.
int val=r/2 ;
int t1[val]; // Not OK
In the second for loop I guess you meant p++ instead of n++;
Instead of manually doing all the memory allocation - deallocation, you should use std::vectors
cout << child; // This outputs the address of the pointer, not the entire array.