Probelm in assigning pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream.h>
#include<conio.h>

void main()
{
 clrscr();
 int ch;
 cout<<"How many elements.....?????";cin>>ch;
 int *p[ch];

 for(int j=0 ;j<ch; ++j)
     *p[j]=j;
 for(j=0 ;j<ch; ++j)
     cout<<*p[j];

 delete p;
 getch();
}


This code when compiled gives an error that "Constant expression required".
Could anyone please get the reason behind it ?????
Please help......
int *p[ch]; needs to be int *p = new int[ch], this will allocate memory for your array and have p point to it. And to delete your pointer, you need to indicate that it's a array you are deleting by using delete [] p and not delete p.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream.h>
#include<conio.h>

void main()
{
 clrscr();
 int ch;
 cout<<"How many elements.....?????";cin>>ch;
 int *p = new int[ch];

 for(int j=0 ;j<ch; ++j)
     *p[j]=j;
 for(j=0 ;j<ch; ++j)
     cout<<*p[j];

 delete [] p;
 getch();
}


Or without using pointers you can do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream.h>
#include<conio.h>

void main()
{
 clrscr();
 int ch;
 cout<<"How many elements.....?????";cin>>ch;
 int p[ch];

 for(int j=0 ;j<ch; ++j)
     *p[j]=j;
 for(j=0 ;j<ch; ++j)
     cout<<*p[j];

 getch();
}



Since you are not using pointers here, p will be allocated on the stack and deleted as soon as it losses it's scope (add the return of you function).
Last edited on
Topic archived. No new replies allowed.