'I'm a newbie in C++,and I 'm now stuck in pointer
I create a function to display the element of an array with position shift to right 3,In case the element overload if will shift to the left, I used pointer to pass by value.The code almost worked but it display 0 instead of input elements. Can somebody show me why, pls!
#include <iostream>
#include <cmath>
using namespace std;
int * sort (const int * const ,int );
void display_origin_order(const int * const ,int );
int * sort(const int * const array,int size)
{
for (int i;i<size;++i)
{
if(i+3<size||i+3==size)
{
cout<<*(array+i+3)<<" ";
}
if (i+3>size)
{
cout<<*(array+i-2)<<" ";
}
}
return 0;
cout<<endl;
}
void display_origin_order(const int * const array,int size)
{
for (int i;i<size;++i)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
int main ()
{
int * first_array{nullptr};
int size{0};
first_array = new int [size];
int init_value{0};
cout<<"Please enter the size of the array \n";
cin>>size;
cout<<"Now its elements \n";
for (int i;i<size;++i)
{
cout<<"input variable \n";
cin>>init_value;
first_array[i] = init_value;
}
cout<<"The array's elements in origin order are : ";
display_origin_order(first_array,size);
cout<<"The array's elements in required order are: ";
sort (first_array,size);
delete [] first_array;
return 0;
}
Solution 1:[1]
The reason you are not prompting for input is because you do not initialize i in your for loops. Your for loops currently are for (int i; i < size; ++i), but should be for (int i = 0; i < size; ++i). If you do not initialize i, then its value is undefined, and it may start with any value which causes the loop to happen any number of times (or no times at all).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
