-4

C++ Program Here is some problem that i faced.After compile it opened a popup window and give me error message "textc.exe has stopped" then i got black screen.

#include<iostream>
using namespace std;
int main()
{
    int i,n,a[10],b[10]//a[10],b[10];
    cout<<"enput array size: ";
  1. List item

    cin>>n;
    cout<<"Enter some number";
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<n;i++)
    {
        b[i]=a[i];
        cout<<"a["<<i<<"]= "<<a[i]<<"\t\t"<<"b["<<i<<"]="<<b[i]<<"\n";
    }
    return 0;
    }
    

If i change my code little bit as like a[10],b[10] instead of a[n],a[n]

then it work perfectly. what is wrong here.

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
Sunil
  • 15
  • 8
  • you are creating an array with an uninitialized size – Tarick Welling May 27 '20 at 10:28
  • What is a[10] - Array of 10 elements. What is a[n] - array of n elements. in you do int n, a[n]; What is the value of n? Its unitialized, so can even be a negative value. So what will be a[n] in that case? That mean you need to initialize n before using in a[n] – Nitesh May 27 '20 at 10:29
  • i want size of array after input value as 'int a[n]; cin>>n;' after taking value of n my array size will be a[10] if i input value of n=10 – Sunil May 27 '20 at 10:40
  • @Skshivangi try to look at : https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers , or https://en.cppreference.com/w/cpp/container/vector . – Gaurav Goswami May 27 '20 at 10:57

1 Answers1

0

Try this way to initialize:

#include <iostream>

int main(void) {
    unsigned int size;
    int *a, *b;

    std::cout << "Enter the size of array: ";
    std::cin >> size;

    a = new int[size]; // dynamic initialization
    b = new int[size]; // of arrays

    for (int i = 0; i < size; i++)
        a[i] = b[i] = 0; // initializing to zero

    for (int i = 0; i < size; i++)
        std::cin >> a[i]; // taking variable of n elements for a

    for (int i = 0; i < size; i++) {
        b[i] = a[i]; // same as a[i], copied
        std::cout << "a[" << i << "] = " << a[i] << "\t\t" << "b[" << i << "] = " << b[i] << '\n';
    }

    return 0;
}

Disclaimer

Array size must be a positive integer and not garbage value and overflowed values are not allowed here too. You can try std::vector<> for dynamic array initialization and also it has a capability of expanding and shrinking.

Rohan Bari
  • 6,523
  • 3
  • 9
  • 30