Hey guys,
First time poster here.:)

Just started my C++ career and am working with pointers/arrays at them moment. I was wondering why I cannot take a user input ('n') to create the size of the array "y". Can anyone show me why this syntax is wrong? Thanks for the help.

#include <iostream>
using namespace std;
int main()
{
  int x[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  int n;
  cin >> n;
  int y[n];  
             
  for (int i = 0; i < n; i++)
    cout << (y[i] = x[i]) << " " ;
  cout<<  endl;
  return 0;
}

i think i can answer this one for you. the compiler has to know how much memory to set asside for the array. so the statement

cin >>x;
array[x];

cant work. however you can fix this problem by using new with a statement like

char* ptr;
ptr = new char[];

arrays must be constant and i dont think getting the index from user input is possible although i maybe wrong. new saves space instead of wasting unused index spaces. (probably not the right terminology). like if i have an array like this char array[10] and the user types a five letter word in. without the use of new the last 5 would be taking up space in memory even though they contain nothing.

Perhaps you should try this like this-
char * ret=new char [n];

for a one dimension array

after this you should input the elements into the array like this:

cin>>n;
int * y=new int [n];
for(int z=0;z<=n-1;z++)
{
   cout<<"element please"<<endl;
cin>>y[z];
}

this is a loop for inputting the user defined values into you 'y' array.
I think it that way.
May it help you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.