It is code to reverse the values as they entered.When I am running the following code. It is taking 8 inputs only. After that it is not printing anything.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
return 0;
}
You can also try the following answer.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = (int *)malloc(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
p--;
cout<<*p<<" ";
}
free(p);
return 0;
}
#include <iostream>
using namespace std;
(Not related to the title, but using namespace std is bad practice that can lead to breakage when switching compilers, for example. Better write the std:: prefix when needed, such as std::cin >>.
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
The above is allocating a single int object, whose value is sizeof(int)*n, and p points to that integer. You probably mean:
int *p = (int*)malloc(sizeof(int)*n); // bad style
... at the end:
free(p);
But using malloc in C++ is a bad idea, unless you want to go closer to the operating system for educational purposes.
Slightly better is to use new, which besides allocating the objects also calls their constructors (but nothing is constructed for basic types such as int).
int *p = new int[n]; // so-so style
... at the end:
delete [] p;
The above is not the best practice because it requires manual memory management. Instead, it is recommended to use smart pointers or containers whenever possible:
std::vector<int> p(n);
// continue with the code, just like with the pointers
Or allocate the individual elements only when needed.
std::vector<int> p;
p.reserve(n); // this is a minor optimization in this case
// ...
if (int value; std::cin >> value)
// This is how to add elements:
p.push_back(value);
else
std::cin.clear();
This looks ok:
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
But this is broken. When the loop starts, p points after the last element. The following *p dereferences a pointer which goes past the last element:
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Replacing the order of pointer decrement and dereference avoids the crash:
for(int j=0;j<n;j++)
{
p--;
std::cout << *p << " ";
}
Ok, there many issues here:
int *p = new int(sizeof(int)*n);
This memory allocation is wrong. It allocates n times sizeof(int) bytes, so if int is 4 bytes long it will allocates n * 4 integers.
int q = n;
q variable is never used.
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
There is no need for pointer arithmetic here. It would be better to access the array in simple p[i] way.
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Same here...
return 0;
}
You allocated memory, but never deallocate. This will cause memory leaks.
A better, correct version of the program could be:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int * p = new int[n];
for (int i = 0; i < n; ++i)
{
cin >> p[i];
}
for (int i = (n - 1); i >= 0; --i)
{
cout << p[i] << ' ';
}
delete [] p;
return 0;
}
Related
As I'm new to c++ I get runtime error for first example(I mean I tested my program with 5 examples it actually happens automatically by a site for testing) of my program I know that's because of exceeding time for running it but I dunno how to fix this.
My program get n numbers from user and finds the largest one and prints it.
#include<iostream>
#include<curses.h>
using namespace std;
int main()
{
int n;
cin >> n;
int *p = new int(n);
for(int i = 1; i<=n; i++){
cin >> *(p+i);
}
int largest = *p;
for(int i = 1; i<=n; i++){
if(largest < *(p+i))
largest = *(p+i);
}
cout << largest;
return(0);
}
int *p=new int(n);
The line above allocates just a single int, and sets the value to n. It does not allocate an array of n integers.
That line should be:
int *p=new int[n];
And then delete [] p; to deallocate the memory.
But better yet:
#include <vector>
//...
std::vector<int> p(n);
is the preferred way to utilize dynamic arrays in C++.
Then the input loop would simply be:
for(int i=0;i<n; i++)
{
cin >> p[i];
}
That same input loop could have been used if you had used the pointer version.
Then you have this error:
for(int i=1;i<=n;i++)
Arrays (and vectors) are indexed starting from 0 with the upper index at n-1, where n is the total number of elements. That loop has an off-by-one error, where it exceeds the upper index on the last loop.
Basically any loop that uses <= as the limiting condition is suspect. That line should be:
for(int i=0; i<n; i++)
(Note that I changed the code above to fix this error).
However ultimately, that entire loop to figure out the largest can be accomplished with a single line of code using the std::max_element function:
#include <algorithm>
//...
int largest = *std::max_element(p, p + n);
and if using std::vector:
#include <algorithm>
//...
int largest = *std::max_element(p.begin(), p.begin() + n);
I've commented on suggested changes in this slightly modified version:
#include <iostream>
int main()
{
unsigned n; // don't allow a negative amount of numbers
if(std::cin >> n) { // check that "cin >> n" succeeds
int* p=new int[n]; // allocate an array of n ints instead of one int with value n
for(int i=0; i < n; ++i) { // corrected bounds [0,n)
if(not (std::cin >> p[i])) return 1; // check that "cin >> ..." succeeds
}
int largest = p[0];
for(int i=1; i < n; ++i) { // corrected bounds again, [1,n)
if(largest < p[i])
largest = p[i];
}
delete[] p; // free the memory when done
std::cout << largest << '\n';
}
}
Note that using *(p + i) does the same as using p[i]. The latter is often preferred.
This would work if all cin >> ... works, but shows some of the hazards when using raw pointers. If extracting the n ints failes, the program will return 1 and leak the memory allocated with new int[n].
A rewrite using a smart pointer (std::unique_ptr<int[]>) that automatically deallocates the memory when it goes out of scope:
#include <iostream>
#include <memory> // std::unique_ptr
int main()
{
unsigned n;
if(std::cin >> n) {
std::unique_ptr<int[]> p(new int[n]);
for(int i=0; i < n; ++i) { // corrected bounds [0,n)
if(not (std::cin >> p[i])) return 1; // will not leak "p"
}
int largest = p[0];
for(int i=1; i < n; ++i) {
if(largest < p[i])
largest = p[i];
}
std::cout << largest << '\n';
} // p is automatically delete[]ed here
}
However, it's often convenient to store an array and its size together and to do this, you could use a std::vector<int> instead. It comes with a lot of convenient member functions, like, size() - and also begin() and end() which lets you use it in range-based for loops.
#include <iostream>
#include <vector> // std::vector
int main()
{
unsigned n;
if(std::cin >> n) {
std::vector<int> p(n); // a vector of n ints
// a range-based for loop, "elem" becomes a refrence to each element in "p":
for(int& elem : p) {
if(not (std::cin >> elem)) return 1;
}
int largest = p[0];
for(int i = 1; i < p.size(); ++i) { // using the size() member function
if(largest < p[i])
largest = p[i];
}
std::cout << largest << '\n';
}
}
That said, you don't need to store any number in an array to figure out what the largest number is. Instead, just compare the input with the currently largest number.
#include <iostream>
#include <limits> // std::numeric_limits
int main()
{
unsigned n;
if(std::cin >> n) {
// initialize with the smallest possible int:
int largest = std::numeric_limits<int>::min();
while(n--) {
int tmp;
if(not (std::cin >> tmp)) return 1;
if(largest < tmp)
largest = tmp;
}
std::cout << largest << '\n';
}
}
#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd
I have created the following program which is supposed to return an int array to the main function, which will then display it on the screen.
#include <iostream.h>
int* returnArray(){
int* arr;
arr[0]=1;
arr[1]=2;
arr[2]=3;
return arr;
}
int main(){
int* res = returnArray();
for(int i=0; i<3; i++){
cout<<res[i]<<" ";
}
return 0;
}
And i was expecting it to print
1 2 3
but instead, it prints 3 someNumberWhichLooksLikeAPointer 0
Why is that? what can i do to return an int array from my function? Thank you very much!
You forgot to allocate your array:
int* arr = new int[3];
You also need to return it, and free the memory inside main after you finish with the loop in order to avoid a memory leak:
delete[] res;
Although this approach works, it is not ideal. If you have an option of returning a container, say, std::vector<int> it would be a much better choice.
If you must stay with plain arrays, another solution for filling an array inside an API is to pass it in, along with its size:
void fillArray(int *arr, size_t s){
if (s > 0) arr[0]=1;
if (s > 1) arr[1]=2;
if (s > 2) arr[2]=3;
}
int main(){
int res[3];
fillArray(res, 3);
for(int i=0; i<3; i++){
cout<<res[i]<<" ";
}
return 0;
}
You have tagged the question with C++. You Yous should consider to use the C++ solution: use a vector of int
#include <iostream>
#include <vector>
std::vector<int> returnArray(){
std::vector<int> arr(3);
arr[0]=1;
arr[1]=2;
arr[2]=3;
return arr;
}
int main(){
std::vector<int> res = returnArray();
for(int i=0; i<3; i++){
std::cout<<res[i]<<" ";
}
return 0;
}
I want to enter n times values for c and e arrays. The following program doesn't allow me to even enter the value of 'n'. Could you tell me where is the mistake?
#include <iostream>
using namespace std;
int main()
{
int n,c[n],e[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
"n" should be defined before using it to fix array size. Also, const int or constant should be used to declare array size not plain int.
In order to use plain datatype, you can initialize array dynamically like
vector<int> a(n); or
int a = new int[n]
int n,c[n],e[n];
This declaration creates arrays c and e on stack with random size, because n as an automatic variable is initialized with random value. Instead you need to dynamically create arrays on heap or use std::vector.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
int n;
vector<int> v;
std::cin >> n;
v.resize( n);
for( int i = 0; i < n; ++i) {
cin >> v[i];
}
for( int i = 0; i < n; ++i) {
cout << v[i];
}
return 0;
}
http://ideone.com/QhgfNv
In the line of
int n,c[n],e[n];
Computer don't know the exact value of 'n', so it can't alloc memory of array.
The simplest solution is create array with fixed number, and check n after you know the value of n as follows:
int n, c[1024], e[1024];
cin >> n;
if (n > 1024) { /* error */ }
The other way is malloc memory after u know the value of n:
int n;
cin >> n;
int *c = new int[n];
int *e = new int[n];
xxxx
delete [] c;
delete [] e;
You can try something like this:
#include <iostream>
using namespace std;
int main()
{
int temp = 100; /*Random value*/
int c[temp];
int e[temp];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
Now, I chose temp as 100, but you can do big as your int can store. Now, if n is lower than temp, your for cycle will let you save your values without troubles.
This is my first time here. I really hope anyone can help me out there. So this is my problem. I keep getting run time error #2 something about a corrupt "arr". But the program runs fine until the end. I can't figure it out.
This is my code:
#include <iostream>
using namespace std;
void main(){
int arr1[3];
int temp;
//INPUT NUMBERS
for (int i=0; i<5;i++)
{
cin>>arr1[i];
}
cout<<endl;
//SORT
for(int c=0;c<5;c++)
{
for (int k=0;k<5;k++)
{
if(arr1[c]<arr1[k])
{
temp=arr1[k];
arr1[k]=arr1[c];
arr1[c]=temp;
}
}
}
for (int m=0; m<5; m++)
{
cout<<arr1[m]<<endl;
}
}
Try this out:
#include <iostream>
using namespace std;
int main()
{
int arr1[5];
int temp;
//INPUT NUMBERS
for (int i = 0; i < 5; i++) {
cin >> arr1[i];
}
cout << endl;
//SORT
for (int c = 0; c < 5; c++) {
for (int k = 0; k < 5; k++) {
if (arr1[c] < arr1[k]) {
temp = arr1[k];
arr1[k] = arr1[c];
arr1[c] = temp;
}
}
}
for (int m = 0; m < 5; m++) {
cout << arr1[m] << endl;
}
}
It compiles properly without any errors. The mistake you had made is in declaring the size of the array. If you want to store 5 in puts, you need to declare an array of size 5. Your code might work, but a good compiler will always give out an error.
The reason being that when you declare an array, you actually create a pointer to the first element of the array. And then, some memory regions are kept for this array, depending on the size. If you try to access an element that is outside these memory regions, you may encounter a garbage value.
Here's your code in ideone.