'Printing out elements of dynamic array or matrix
Why does this simple code for printing out an array not work?
void main()
{
cout<<"Simple for\n";
int n;
cout<<"Enter the lenght of array:";
cin>>n;
int* a= new int[n];
for(int j=0; j<n; j++){
a[j]=0;
cout<<setw(8)<<a[j];
//getchar();
}
getchar();
delete[]a;
}
The output disappears quickly.
When n is constant its works but when n comes from input it doesn't work. When getchar put in the For, it only prints out two elements of the array with any length.
What is wrong?
Solution 1:[1]
You probably want this:
int* a= new int[n];
C++ is not C; you don't allocate "bytes" with new; you allocate objects. Arrays, types, etc. So if you want an array of n values of type int, then you allocate that. No need for sizeof, multiplication, etc.
Note that anything you allocate with the array version of new (ie: new Type[]) must be deleted with the array version of delete:
delete []a;
The size is unnecessary; you just need to make sure that new[] is paired with delete[]
Solution 2:[2]
This allocation
int* a= new int(n*sizeof(int));
only allocates a single int and sets its initial value to n*sizeof(int). Not exactly what you wanted.
The correct way to allocate n ints is
int* a = new int[n];
or even better
std::vector<int> a(n);
Solution 3:[3]
Thanks everyone The problem is solved.. But I don,t know why. Can anyone explain the role of another getchar() here?
This is new code:
int main()
{
cout<<"Simple for\n";
int n;
cout<<"Enter the lenght of array:";
cin>>n;
int* a= new int[n];
for(int j=0; j<n; j++){
a[j]=0;
cout<<setw(8)<<a[j];
}
delete[]a;
getchar();
getchar();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Bo Persson |
| Solution 3 | Susan |
