Jump to content

Declaring array with number of rows from input

- - - - -

  • Please log in to reply
4 replies to this topic

#1
kristoffera

kristoffera

    Newbie

  • Members
  • Pip
  • 2 posts
Hi.

I want to declare an array of integer, but I want the program to take input from user on how many rows the array should hold. How can I do this?

I've tried:

int nCities;
cin>>nCities;
int cities[nCities][nCities];

but didn't work.

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1

int nCities;

cin >> nCities;


int** cities;

cities = new int* [nCities];

for (int i = 0; i < nCities; ++i)

    cities[i] = new int[nCities];

...

for (int i = 0; i < nCities; ++i)

    delete cities[i];

delete [] cities;


A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
>>int cities[nCities][nCities];

I think that will be allowed in the next version of c++ standards. But the compilers will probably take about 4 to 5 years to implement it. I have not tried it yet but I think the newest version of g++ supports it.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4
kristoffera

kristoffera

    Newbie

  • Members
  • Pip
  • 2 posts
So what does this do exactly? I'm a little confused

int** cities ---> cities is a pointer to a pointer to an integer?
cities = new int* [nCities] ---> what cities points to is an array of pointers with nCities elements ??
for (int i = 0; i < nCities; ++i)
cities[i] = new int[nCities]; ---> hmm ?

#5
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1

kristoffera said:

So what does this do exactly? I'm a little confused

int** cities ---> cities is a pointer to a pointer to an integer?
cities = new int* [nCities] ---> what cities points to is an array of pointers with nCities elements ??
for (int i = 0; i < nCities; ++i)
cities = new int[nCities]; ---> hmm ?
Yeah, since we want 2 dimensional array we need [I]double pointer. Then we create first dimension of pointers and in for loop we create another dimension in i-th dimension.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users