How do i set an array to have custom lenght? [closed] - c++

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 2 years ago.
Improve this question
I am getting an error when i run this code. The error code is 0xC00000FD and I can't seem to find a fix for what i need. Can someone please help me? Here's the code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n;
int arr[n];
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}

There are two major problems in your code. First, C++ does not have "variable length arrays" (VLAs), although some compilers support them as an extension.
More importantly, even if your compiler does support them, you are attempting to define the size of your arr before you have read the value of n.
To fix these issue you should: (a) use the std::vector container, rather than a plain array; and (b) only declare that after you have read in the value of n.
Here's a 'quick fix':
#include <iostream>
#include <conio.h>
#include <vector> // For the "std::vector" definition
using namespace std;
int main()
{
int n;
// int arr[n]; // Here, the value of "n" is undefined!
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
std::vector<int> arr(n); // This can now be used 'almost' like a plain array
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}

Standard C++ does not support variable length arrays. std::vector can accomplish what you want. It is also possible to allocate memory of the desired size with new int[size] and use a pointer to reference the data rather than an array. However, this doesn't have any bounds checking, so there is the possibility of memory corruption. And the allocated memory must be explicitly freed with delete[]. So std::vector is my preferred solution.

Related

I'm a beginner and i dint understand what the error is. Can you help girl? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Create and print two source arrays of real numbers X(N) , Y(M) (S decimal places). Define an array with fewer negative elements. Use functions: initialization with random numbers, output, determining the number of negative elements in arbitrary arrays of integers. C++. Compilation is fine, but displays an error "Segmentation fault (core dumped)"
enter code here
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <math.h>
#include <time.h>
using namespace std;
const int S=2;
void init(double a[], int n, double b[], int m) {
int c=0, k=0;
srand(time(0));
cout<<"Enter the number of elements in the array X:";
cin>>n;
cout<<"Array X is:";
for(int i=0; i<n;i++) {
a[i]=rand()%50-100/3.;
cout.precision(S);
cout<<setw(8)<<fixed<<a[i]<<" ";
}
for (int i=0; i<n; i++)
if (a[i]<0) c++;
cout<<endl;
cout<<"Enter the number of elements in the array Y:";
cin>>m;
cout<<"Array Y is:";
for(int i=0; i<m;i++) {
b[i]=rand()%50-100/7.;
cout.precision(S);
cout<<setw(8)<<fixed<<b[i]<<" ";
}
for (int i=0; i<m; i++)
if (b[i]<0) k++;
cout<<endl;
cout<<"Total negative elements in the array X: "<<c<<"."<<endl;
cout<<"Total negative elements in the array Y: "<<k<<"."<<endl;
if(c>k)
cout<<"Array X has more negative elements than array Y."<<endl;
else if (c<k)
cout<<"Array Y has more negative elements than array X."<<endl;
else
cout<<"Array X and array Y have the same number of negative elements."<<endl;
}
int main() {
int N, M;
double X[N],Y[M];
init(X,N,Y,M);
return 0;
}
In C++, you can't declare an array with a size read from input. You especially can't declare it with a size that will be read from input later.
If you want a dynamically sized array, use std::vector.
#include <iostream>
#include <vector>
#include <math.h>
#include <time.h>
void init() {
srand(time(0));
std::cout<<"Enter the number of elements in the array X:";
std::size_t n
std::cin >> n;
std::vector<double> a(n);
std::cout<<"Array X is:";
for(int i=0; i<n;i++) {
a[i]=rand()%50-100/3.;
cout.precision(S);
std::cout<<setw(8)<<fixed<<a[i]<<" ";
}
int c = 0;
for (int i=0; i<n; i++)
if (a[i]<0) c++;
std::cout<<std::endl;
std::cout<<"Enter the number of elements in the array Y:";
std::size_t m;
std::cin>>m;
std::vector<double> b(m);
std::cout<<"Array Y is:";
for(int i=0; i<m;i++) {
b[i]=rand()%50-100/7.;
cout.precision(S);
std::cout<<setw(8)<<fixed<<b[i]<<" ";
}
int k = 0;
for (int i=0; i<m; i++)
if (b[i]<0) k++;
std::cout<<endl;
std::cout<<"Total negative elements in the array X: "<<c<<"."<<std::endl;
std::cout<<"Total negative elements in the array Y: "<<k<<"."<<std::endl;
if(c>k)
std::cout<<"Array X has more negative elements than array Y."<<std::endl;
else if (c<k)
std::cout<<"Array Y has more negative elements than array X."<<std::endl;
else
std::cout<<"Array X and array Y have the same number of negative elements."<<std::endl;
}
int main() {
init();
return 0;
}
using namespace std is a bad habit. If your instructor tells you to use it, they are wrong.
Look at std::uniform_real_distribution along with a generator from <random> for generating random doubles between two limits.
Look at std::count_if with a function bool isNegative(double x) { return x < 0 } for counting how many numbers are negative.

C++ Array passing to function with size [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 2 years ago.
Improve this question
I am writing C++ code to get the maximum number from an array of integers using a function.
My code is as follows, but it's not working and I can't seem to fix it, I would like to know, if possible, what's wrong with it:
#include<iostream>
using namespace std;
int maxfunc(int myArr, int size);
int main()
{
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
for(int i=0; i<size; i++)
{
cout<<"Value No. "<<i+1<<" : ";
cin>>arr[i];
}
int max = maxfunc(arr,size);
cout<<"max = "<<max;
}
int maxfunc(int myArr, int size)
{
int largest=myArr[0];
for(int i=1; i<size; i++)
{
if(largest<myArr[i])
{
largest=myArr[i];
}
}
return largest;
}
In
int maxfunc(int myArr, int size)
The argument int myArr is an integer but you are using it as an array of integers.
I would use a pointer to the original array:
int maxfunc(int *myArr, int size)
Another problem that stands out is that you are using size variable uninitalized, my gess is that you are missing a cin >> size;:
cout<<"Enterv the size of array: ";
cin >> size;
Finally, and this is opinion based, this is the kind of program you would use in C, for C++ there are better tools for storing a manipulating data. For this case I would recommend std::vector or if the array is ment to have fixed size, std::array.
You did not entered the size of the array
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
So the program has undefined behavior.
Also the function implementation is wrong because in general the user can pass the second argument equal to or less than 0.
The function should be declared like
size_t maxfunc( const int myArr[], size_t size);
^^^^^^^^^^^^^^^^^
and it should return the index of the maximum element.
The function can be implemented like
size_t maxfunc( const int myArr[], size_t size )
{
size_t largest = 0;
for ( size_t i = 1; i < size; i++ )
{
if ( myArr[largest] < myArr[i] )
{
largest = i;
}
}
return largest;
}
And in main you can write
size_t max = maxfunc( arr, size );
cout << "max = " << arr[max] << '\n';
delete []arr;
Do not forget to free the allocated memory.
Pay attention to that in C++ there is the standard algorithm std::max_element declared in the header <algorithm> that does the task. It returns iterator that points to the maximum element.

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

SIGSEGV when sorting array with C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I tried sorting this array in ascending order and I got reply saying RUNTIME error(SIGSEGV). Can Anybody explain ?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, arr[1000];
cin >> n;
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
sort(arr, arr + n);
for (int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
When you get input from a user that is used to populate an array, you should always validate the input before using it. If the user wants to enter 1001 numbers or more, or even a negative amount, you will access the array out of bounds and your program has undefined behaviour.
A better alternative is to use a std::vector to allocate just as much space as you need. One possible solution:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
size_t n;
if(std::cin >> n) { // check that the user actually entered a number
std::vector<int> arr(n); // create a vector with n elements
for(size_t i=0; i<n; ++i)
std::cin >> arr[i];
std::sort(std::begin(arr), std::end(arr));
for(size_t i=0; i<n; ++i)
std::cout << arr[i] << '\n';
}
}
You're allocating space for only 1000 elements, thereby causing segmentation fault if n is more than that, because scanf will try to put 1001-th element in memory location un-allocated to arr. Since you're using C++, Please use std:vector to avoid such pitfalls.

Why my coding got error cannot convert int to int * in function main ? [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 9 years ago.
Improve this question
#include<iostream.h>
void main()
{
int i[10], sum, n1, n2, size;
cout<<"Enter size array :";
cin>>size;
for(i=0; i<size; i++)
{
cout<<"Enter number 1 :";
cin>>n1[i];
cout<<"Enter number 2 :";
cin>>n2[i];
sum[i]=n1[i]+n2[i];
}
cout<<"sum : "<<sum;
}
i have no idea. please help me . it also stated there Lvalue required in function main.
int i[10], sum, n1, n2, size;
You declare i to be an array, but you use it like it's a single value. You try to index sum, n1, and n2 by writing [i] after them in the loop, but they're not declared as arrays.
Recommendation: change your variable declarations.
int i, sum[10], n1[10], n2[10], size;
I think you have to try this:
#include<iostream>
int main()
{
int i, sum[10], n1[10], n2[10], size;
cout<<"Enter size array :";
cin>>size;
for(i=0; i<size; i++)
{
cout<<"Enter number 1 :";
cin>>n1[i];
cout<<"Enter number 2 :";
cin>>n2[i];
sum[i]=n1[i]+n2[i];
cout<<"sum : "<<sum[i] << endl;
}
}