Shivam Sahil
Shivam Sahil

Reputation: 4921

C++ Input space separated integers and store inside an int array

I am trying to input int array size and then get N space-separated integers as shown below:

int main()
{

    int N;
    cin>>N;
    int *arr = new int(N);
    for(int i=0; i<N; i++) {
        cin>>arr[i];
    }

for(int i=0; i<N; i++) {
        cout<<arr[i]<<endl;
    }
 
    if (isSpiralSorted(arr, N))
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    return 0;
}

but the input:

10
1 2 3 4 5 6 7 8 9 10

actually takes:

2 3 4 5 6 7 8 9 10

Can someone help me here in understanding what am I doing wrong?

Upvotes: 0

Views: 749

Answers (1)

Henrique Bucher
Henrique Bucher

Reputation: 4474

You are creating a single scalar with new int(N) and not an array. If you change it to new int[N] then it runs fine.

Also you forgot to delete the array in the end.

#include <iostream>

int main()
{
    int N;
    std::cin >> N;
    int *arr = new int[N];
    for(int i=0; i<N; i++) {
        std::cin>>arr[i];
    }

    for(int i=0; i<N; i++) {
        std::cout << arr[i] << std::endl;
    }
    delete[] arr;
}

Godbolt: https://godbolt.org/z/caza1336s

Upvotes: 3

Related Questions