How to allocate memory dynamically using pointers? - c++

I have the following task:
Creat a program that will transform array A to array B in the followin order:
http://gyazo.com/29e434ebdc1e235fe0fc97c26ae9fe9c
The size of A is entered by user, as well the elements. Print the new elements of B. "Use pointers"
Examples: If I input 1234567, the program will output 8888888.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int N;
cout << "Enter the size of array" << endl;
cin >> N;
int A[N], B[N];
cout << "Enter the elements of the array" << endl;
for(int i = 0; i < N; i++){
cin >> A[i];
}
for(int i = 0; i < N; i++){
B[i] = A[i] + A[N-i-1];
}
for(int i = 0; i < N; i++){
cout << B[i] << " ";
}
return 0;
}
There is only one problem I have, it says to "use pointers" but I don't know where shall I use them and they must be used... thanks in advance.

int A[N], B[N];
This code is non-standard (when N is a variable). Your compiler allows that, but if you try to compile this code in other one, it probably won't work.
Using pointers in this case means, that you should allocate memory for the arrays dynamically, eg.
int * A, * B;
A = new int[N];
B = new int[N];
This code is valid in terms of C++ standard.
Remember though, that you will have to free allocated memory manually after you don't need it anymore:
delete[] A;
delete[] B;
This should work with the rest of your code left unchanged, since [] operator works for pointers as well.
And finally, if you really are writing a C++ program, you surely should be using std::vector instead of C-style arrays...
Edit: (in response to comment)
If you declare a variable in the following way:
int * A;
And then write:
cin >> *(A + i);
It means:
Read data from user and parse it;
Go i "steps" starting from address A (it actually "walks" i * sizeof(*A) bytes from A).
Put the data read from the user to memory pointed to by place evaluated in step 2.
But when you declare:
int (*A)[N];
The A becames pointer to the array of N elements. Since array is convertible to a pointer to its first element, you may think of that previous line (for the sake of explanation) as
int ** A;
In such case compiler tries to do the same as I described earlier. But now it walks i pointers starting from A, not *int*s. Then it dereferences that pointer getting an int * and attempts to put there data written by user. But >> operator of cin is not able to translate text to a pointer and that's why compiler complains.
Foot note
While you're learning using pointers, you may think of <something> variable[] as being equal to <something> * variable pointing to the first element of that array. This is a lie (because array is not a pointer, but it's convertible to a pointer to its first element), but helps understanding what arrays do have in common with pointers. That's why you can think of
int (* A)[];
As a
int ** A;

Well, this
cin >> N;
int A[N], B[N];
is not valid ANSI C++. You cannot declare arrays with variable indices. So you need a way to declare variable length arrays, and one way is to use pointers and dynamically allocated memory using new[] (and then delete[]).
The other, preferable method would be to use a container such as std::vector.

Related

Normal array declaration vs. dynamic array declaration

I just started learning C++. I learned the easy way of declaring arrays and now I'm confused about the usage of
int* foo = new int[n];
and how it is different from
int foo [n];
I tried testing with code but couldn't find any difference. I read from sources that using "new" requires me to manually de-allocate the memory after I don't need it anymore. In that case, there is no advantage in using "new" or dynamic memory allocation at all. Am I missing something here?
I tried running this:
#include <iostream>
int main() {
int n;
std::cout << "array size" ;
std::cin >> n ;
std::cout << n ;
int foo [n]; //line A
// int* foo = new int[n]; //line B
foo[6] = 30;
std::cout<<foo[6]<<std::endl;
}
Commenting out line B to run line A, or vice versa, gave the exact same result.
There are several ways these are different. First, let's talk about this one:
int n = 10;
int array[n];
This is not part of the ANSI C++ standard and may not be supported by all compilers. You shouldn't count on it. Imagine this code:
int n = 10;
int array[n];
n = 20;
How big is array?
Now, this is the way you can do it (but it's still problematic):
int n = 10;
int * array = new int[n];
Now, that is legal. But you have to remember later to:
delete [] array;
array = nullptr;
Now, there are two other differences. The first one allocates space on the stack. The second allocates space on the heap, and it's persistent until you delete it (give it back). So the second one could return the array from a function, but the first one can't, as it disappears when the function exits.
HOWEVER... You are strongly, strongly discouraged from doing either. You should instead use a container class.
#include <array>
std::array<int, n> array;
The advantages of this:
It's standard and you can count on it
You don't have to remember to free it
It gives you range checking

What the error in my code. I try to use array in class but getting logical error

I try to make an array and take input and then simply showing the output on the screen but uses classes and objects, Here is my code:
#include<iostream>
using namespace std;
class array{
int ar[], n;
public:
void input();
int display();
}obj;
void array::input(){
cout<<"Enter item size: ";
cin>>n;
int ar[n]={};
for(int i=0; i<n; i++){
cout<<"Enter value at index "<<i<<" : ";
cin>>ar[i];
}
}
int array::display(){
cout<<"You Entered: ";
for(int i=0 ; i<n; i++){
cout<<ar[i];
}
}
int main(){
obj.input();
obj.display();
}
In the sample run, I entered 1 and 2 and I am expected to get 1 and 2.
Two problems in your code.
First int ar[] should not compile. I get the following error:
prog.cc:4:12: error: ISO C++ forbids flexible array member 'ar' [-Wpedantic]
int ar[], n;
^
Next, in array::input() you create a completely new array int ar[n]={}; which is also not valid c++. Array sizes must be compiletime constants. Moreover, this array shadows the member and is unrelated to it (apart from having the same name). So this ar is gone once you return from the method. You never write anything into the member ar.
If you dont know the size in advance you should use a std::vector:
#include <iostream>
#include <vector>
class array{
std::vector<int> ar;
public:
void input();
int display();
};
void array::input(){
std::cout << "Enter item size: ";
int n;
std::cin >> n;
ar.resize(n);
for(int i=0; i<n; ++i){
std::cout << "Enter value at index " << i << " : ";
std::cin >> ar[i];
}
}
int array::display(){
std::cout<<"You Entered: ";
for(int i=0 ; i<n; ++i){
std::cout << ar[i];
}
}
int main() {
array obj;
obj.input();
obj.display();
}
PS: read here why using namespace std; is bad practice: Why is "using namespace std" considered bad practice?
IMHO user463035818s answer is sufficient, but for all that OP asked me
how to fix this compiler issue.
The recommended fix would be by design i.e. like shown in user463035818s answer.
So, I want to elaborate how to fix the sample code of OP (with "minimal" changes). That might make obvious why user463035818s answer is the better one. (I repeated the link three times – it should be clear to everybody that I consider this as the better solution.)
The actual compiler error (or warning or feature accepted by compiler extension):
OP used int ar[] a C array as class member without denoting the size.
This is called Flexible array member but it is a C99 feature (not supported by the C++ standard).
The linked Wikipedia article provides a nice example:
struct vectord {
size_t len;
double arr[]; // the flexible array member must be last
};
To be clear, flexible array members don't provide automatic allocation. They just represent an array of arbitrary length. The programmer is responsible to grant sufficient storage for that array. Hence even in C, and with the resp. syntax adjustments, this code would have been broken.
Some C++ compilers adopt features from C as (proprietary) extension. That's the reason that OP got responses ranging from "On my side, it works."1 to "This is a compiler error." However, I would consider usage of such extensions as bad style in general. With different compiler settings or a different compiler, this might not work anymore.
1 This is not the only issue of OPs code. "It works" might be merely bad luck. OPs code has Undefined Behavior. One kind of Undefined Behavior is "It works" which is not the best one because programmer might believe that the code is fine.
A lot of higher level languages (Java, C#, Python) tries to cover memory allocation and storage management "under the hood" completely because it's not quite easy to make this always correct and consider every edge case sufficiently. This might cause an additional performance impact for the administration of memory. In C and C++, the programmer has ful control over memory allocation. It's both a blessing and a curse.
The standard library of C++ provides a variety of tools to make programmers allocation life easier.
For dynamic arrays, the tool of choice is the template class std::vector. It provides an overloaded operator[] which allows that it can be accessed just like an array. It provides methods like reserve() and resize(). The storage is internally managed.
I would strongly recommend to use std::vector but there is also the possibility to do it using new[] and delete[].
For this, the class array might look as follows:
class array {
int *ar; // a raw pointer for storage
int n; // the current size of array
public:
int display();
int* and int are plain old data types → implicit construction leaving them uninitialized. So, there really should be defined at least a default constructor.
array(): ar(nullptr), n(0) { }
The input() method has to ensure proper storage.
void input()
{
// release old memory (if there is one)
delete[] ar; ar = nullptr; n = 0;
// input
std::cout << "Enter item size: ";
std::cin >> n;
if (n <= 0) return;
ar = new int[n];
for (int i = 0; i < n; ++i) {
std::cout << "Enter value at index " << i << ": ";
std::cin >> ar[i];
}
}
When an instance of class array is deleted it should release the internal storage. Otherwise, the allocated memory pointed by ar will be orphaned and lost until process is terminated by OS. Such lost memory is called memory leak.
~array() { delete[] ar; }
Please, note that calling delete[] (or delete) with a nullptr is valid. Hence, no extra if (ar) is needed.
Finally, we have to obey the Rule of three. The compiler generates implicitly copy constructor and copy assignment operator which will copy the class array members by value. Copying a pointer by value does not mean that the contents (it points to) is copied. It just means copy the pointer (address value). Hence, an (accidental, unintended) copy of class array could result in two instances of class array which members ar point to the same memory. Once, one of them deletes that memory, the ar of the other becomes dangling i.e. points to released memory. (Bad!) If the other instance is destroyed also it will delete[] ar again. This is double deleting which is prohibited. (Bad again!)
One option could be to define copy constructor and copy assignment to handle this appropriately by making a deep copy of ar contents (with another new[]). However, if copy is not intended, an alternative is to just explixitly prohibit copy for class array:
array(const array&) = delete;
array& operator=(const array&) = delete;
};
Putting this althogether in array.cc:
#include <iostream>
class array {
int *ar; // a raw pointer for storage
int n; // the current size of array
public:
array(): ar(nullptr), n(0) { }
~array() { delete[] ar; }
array(const array&) = delete;
array& operator=(const array&) = delete;
void input();
void display();
};
void array::input()
{
// release old memory (if there is one)
delete[] ar; ar = nullptr; n = 0;
// input
std::cout << "Enter item size: ";
std::cin >> n;
if (n <= 0) return;
ar = new int[n];
for (int i = 0; i < n; ++i) {
std::cout << "Enter value at index " << i << ": ";
std::cin >> ar[i];
}
}
void array::display()
{
std::cout << "You Entered: ";
for (int i = 0; i < n; ++i) {
std::cout << ar[i];
}
std::cout << '\n';
}
int main()
{
array obj;
obj.input();
obj.display();
return 0;
}
Compiled and tested:
$ g++ -std=c++11 -Wall -pedantic array.cc && ./a.out
Enter item size: 1↲
Enter value at index 0: 2↲
You Entered: 2
$
Live Demo on coliru
The last sentence in OPs question is a bit unclear for me (although I assume it's just bad worded):
In the sample run, I entered 1 and 2 and I am expected to get 1 and 2.
Either input is 2 1 2 then output is 1 2.
Or input is 1 2 then output is 2.
Please note that array::input() expects first input of array::n but array::display() doesn't output array::n.

Array of pointers to structs

EDIT: Im quite new to c++ and programming as a whole.
I'm supposed to make a program where i use stucts and and an array of structs.
Security council < > Member of Security council
My task was to use the concept of "UML aggregation" to create a program where I use structs and struct arrays. (I hope you understand what I'm trying to say)
Since a Member of a Security council is a part of a Security council, and not the other way around, the struct of Security council must have an array of its members.(bear with me)
//example
struct Member_sc{
char * name;
int age;
};
struct Security_council{
Member_sc members[10];
};
Now, I've created this program and everything works perfectly (according to my teacher), but now she told me create an exact copy, but instead of the "members" array I must use an array of pointers to the Member_sc structs. Since I havent completely figured out how pointers work, I have come across some problems.
I can post the code to the original program if needed, but it contains 4 files(main, header, and some function files) and it would be a pain to try and post it here.
here is the prototype (all in one file, for now)
#include <iostream>
using namespace std;
struct member_sc{
string name;
};
struct security_council{
member_sc *point;
security_council **search; // ignore this for now
int n;
security_council():n(0){}
};
void in_mem( member_sc &x){
getline(cin,x.name);
}
void out_mem(member_sc &x){
cout<<x.name<<endl;
}
void in_SC(security_council &q, member_sc &x){
int num; //number of members
cin>>num;
for(int i=0; i<num; ++i){
in_mem(x);
q.point[q.n]=x;
q.n++;
}
}
void out_SC(security_council &q,member_sc &x){
for(int i=0; i<q.n; ++i){
out_mem(q.point[i]);
}
}
int main(){
member_sc y;
security_council x;
in_mem(y); // works
out_mem(y); // works
in_SC(x,y); // crashes after i input the number of members i want
out_SC(x,y); //
system("pause");
return 0;
}
The program crashes after you input the number of members you want in your Security council.
Is my way of thinking right? or should I use dynamic memory allocation?
in addition to that (my teacher gave me an additional task) create a search function using pointers. i thought that pointer to pointer may be good for that, but im not sure.
Any help or advice would be greatly appreciated.
( i think ill figure out the search thingy once i figure out how pointers to structs work)
The first part of your issue is this:
cin >> num;
this reads only the digits that have been typed and stops at the newline. Then, in in_mem the call to getline immediately reads a newline. You need to do:
cin >> num;
cin.ignore();
this will drain the input stream of any remaining input, or catch up so to speak.
However your core problem is that you don't allocate any memory for "point" to point to.
A pointer is just a variable holding a value that happens to be the address (offset from 0) of a thing in memory. If you are going to the airport and write "Gate 23" on a post-it note, the post it note is a pointer and "Gate 23" is the value.
In your code, that variable is uninitialized and will either be 0, if you are lucky, or some random address in memory if you aren't so lucky.
To the airport analogy: you arrive at the airport and find that your post-it note has "pizza" written on it. Not helpful.
Your teacher has actually specified an "array of pointers". Break that down: pointer to what? member_sc, that's member_sc*. And now make it an array
member_sc* pointers[10];
NOTE: This is not good, modern C++ - in modern C++ you would use something called a smart pointer (std::unique_ptr) probably.
std::unique_ptr<member_sc[]> pointers(new member_sc[10]);
Now you have 10 pointers instead of just one, and all of them will need some allocation to point to. The easiest way to do this is with the new keyword and the copy constructor:
for (int i = 0; i < num; i++) {
in_mem(x);
pointers[q.n] = new member_sc(x); // make a clone of x
q.n++;
}
or in modern C++
for (int i = 0; i < num; i++) {
in_mem(x); // x is temporary for reading in
pointers[q.n] = std::make_unique<member_sc>(x);
q.n++;
}
However there is a limitation with this approach: you can only have upto 10 security council members. How do you work around this? Well, the modern C++ answer would be to use a std::vector
std::vector<member_sc> members;
// ditch n - vector tracks it for you.
// ...
for (int i = 0; i < num; ++i) {
in_mem(x);
q.members.push_back(x);
// q.n is replaced with q.members.size()
// which is tracked automatically for you
}
but I'm guessing your teacher wants you to actually understand pointers before you get to forget about them with modern luxuries.
We need to re-use the pointer stuff we've just used above and change "pointers" to an array of pointers.
Which means we're going to want a pointer to a set of pointer-to-member_sc.
member_sc** pointers;
We'll need to assign some memory for this to point to:
cin >> num;
cin.ignore();
if (num == 0) {
// do something
return;
}
pointers = new member_sc[num];
luckily, using a pointer to an array is as easy as using an array, the only major difference being that you lose the size-of-array information -- all you have is the address, not the dimensions.
for (int i = 0; i < num; i++) {
in_mem(x);
q.pointers[i] = new member_sc(x);
q.n++;
}
I'm deliberately not providing you with a complete working example because this is obviously for a class.
You never initialize the memory that the point member refers to, yet then in statement q.point[q.n]=x; you attempt to use it.
Basically, after you read in the number of members, and before the for loop where you read in the individual members, you need to allocate an array of an appropriate number of member_sc objects and store it in q.point. Don't forget to free this memory when done using it.
Once you do that, you can also remove the member_sc &x argument from both in_SC and out_SC, as that will become unnecessary.
Finally, some validation of your input seems to be in place. Consider what will happen if the user enters a negative number, and you attempt to use that directly to determine the size of memory to allocate.
Here's a simple example showing how to use a dynamically allocated array of structures:
#include <iostream>
#include <string>
struct member_sc {
std::string name;
};
void test_array(int count)
{
if (count <= 0) {
return; // Error
}
// Allocate an array of appropriate size
member_sc* members = new member_sc[count];
if (members == nullptr) {
return; // Error
}
// ... fill in the individual array elements
for(int i(0); i < count; ++i) {
// ... read from input stream
// I'll just generate some names to keep it simple
members[i].name = "User A";
members[i].name[5] += i; // Change the last character, so we have different names
}
// Now let's try printing out the members...
for(int i(0); i < count; ++i) {
std::cout << i << ": " << members[i].name << "\n";
}
delete[] members;
}
int main(int argc, char** argv)
{
for(int count(1); count <= 10; ++count) {
std::cout << "Test count=" << count << "\n";
test_array(count);
std::cout << "\n";
}
return 0;
}
Example on Coliru
Of course, there are many other issues with this style of code, but I believe that's beside the point of this question. For example:
Instead of using bare pointers, it would be more appropriate to use some kind of a smart pointer.
Instead of a simple array, use some kind of collection, such as a vector.
Since you are asked to use an array of pointers, do so: replace
Member_sc members[10];
with
Member_sc* members[10];
Then fill out that array using dynamic memory allocation. As a matter of good form, at the end of the program remember to release the dynamic memory you have used.

C++ Passing Static Array and Dynamic Array By Reference

To fully understand how pointers, values, and references work, I am making a basic C++ program that attempts to tamper with some static and dynamic arrays and understand exactly how they should be passed in.
First I generate a static array of 3 elements. I then pass it into a function that modifies all elements. I then pass it into another function with a slightly different signature, but can also alter the array's values.
Next I generate a dynamically sized array, pass it into a function by reference so that all of the values in this dynamically sized array can be altered.
The code is as follows:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void changeIndexStaticArrayMethod1(int* stat);
void changeIndexStaticArrayMethod2(int (&stat)[3]);
void changeIndexDynamicArrayMethod1(int* dyn, int size);
int main() {
const int MAX = 3;
int arr[MAX] = { 1,2,3 };
changeIndexStaticArrayMethod1(arr);
cout << arr[0] << endl;
cout << arr[1] << endl;
cout << arr[2] << endl;
cout << endl;
changeIndexStaticArrayMethod2(arr);
cout << arr[0] << endl;
cout << arr[1] << endl;
cout << arr[2] << endl;
int SIZE;
cout << "Please choose a size for the array" << endl;
cin >> SIZE;
int *ne = new int[SIZE];
//Build array
for (int i = 0; i < SIZE; i++) {
ne[i] = i;
}
changeIndexDynamicArrayMethod1(ne, SIZE);
for (int i = 0; i < SIZE; i++) {
cout << "ne[" << i << "] = " << ne[i] << endl;
}
//To hang program
cin >> SIZE;
delete[] arr;
delete[] ne;
return 0;
}
void changeIndexStaticArrayMethod1(int* stat) {
stat[0] = 10;
stat[1] = 20;
stat[2] = 30;
}
void changeIndexStaticArrayMethod2(int (&stat)[3]) {
stat[0] = 40;
stat[1] = 50;
stat[2] = 60;
}
void changeIndexDynamicArrayMethod1(int* dyn, int size) {
for (int i = 0; i < size; i++) {
dyn[i] = i * 10;
}
}
All of the above code works how I want it to, I just have a few questions as to why (some of the methods of passing arrays by reference I have found on other SO questions).
In the changeIndexStaticArrayMethod1() and changeIndexDynamicArrayMethod1() functions, why are we able to use the dereference * operator for our array as reference? My knee jerk reaction is seeing that as practically passing the array in by values since it is the dereference operator. I know that with arrays, it is much different than using variables, but also, why will the following not work for single int variables:
void changeStaticNumber(int* num){
num = 100;
}
Obviously the above will work if we use &num and not int* num, and obviously I don't fully understand the relationship between pointers and arrays, but I cannot figure out why when we pass an array by reference, int* staticArray is ok.
Any explanation for these problems I am having would be much appreciated. Thanks.
why are we able to use the dereference * operator for our array as reference?
The * in C means many things. It can mean the unary indirection ("contents of") operator, it can mean the binary multiplication operator and it can mean a pointer declaration. The int* stat is a pointer declaration.
Since you aren't using the * to dereference the contents of the pointer inside that function, I'm not quite sure what you are asking.
When you take the array name of your array in main(), it "decays" into a pointer to the first element. So what those function do, is to take a pointer by value. If you dereference the pointer by typing *stat = something; you access the actual array in main.
Should you do something weird like changing the pointer itself, for example stat++;, then it will not affect the address used in main. You passed the pointer itself by value, so the pointer is a local copy.
My knee jerk reaction is seeing that as practically passing the array in by values since it is the dereference operator.
You can't really pass arrays by value in C or C++, without resorting to dirty tricks (storing them inside structs or classes). For example, had your function been written as void changeIndexStaticArrayMethod1(int stat[3]) it would still give you a pointer to the first element. It will not pass an array by value, as the syntax might trick you into believing.
why will the following not work for single int variables:
void changeStaticNumber(int* num){ num = 100; }
Because num is the pointer itself, not its contents. In order to write code like that, you could pass the variable by reference int& num. Behind the lines this is really the same thing as passing a pointer, just with simplified syntax.
To understand the relation between pointers and arrays better, start by reading this whole chapter: http://c-faq.com/aryptr/index.html (C and C++ are identical when it comes to pointers).
Let me see if I can take a stab at this.
Pointers are simply address holders. Once you do int * ptr = myarray; --- what you are in tern doing is storing the address of the pointer my array into ptr --- array names are actually pointers to the first memory location in the array. You can use pointer arithmetic to get at everything else for example myarray +1 will point you to the next location or myarray[1].
Passing by value is not very useful when you need to modify your array. Passing in by reference is essentially making a pointer to the array and passing that. Since arrays like vectors are contiguous blocks of memory you can index through them rather easily.
As far as your example goes void changeStaticNumber(int* num){ num = 100; } will not work because what you are attempting to do is store 100 into the pointer's address. If you deference num and make it void changeStaticNumber(int* num){ *num = 100; } it will work because you are actually going one step further and accessing the data that num is pointing to. When you use &num it is essentially the same thing - & just gives you the address of something.
For example if you want to point a pointer to an int what you would do is
int num = 5;
int *ptr = &num;
at this point in time ptr has the same address in num. To print out the data in num or that ptr is pointing to you need to dereference or go one step further as I like to tell myself and dereference to so cout << *ptr;
In both changeIndexStaticArrayMethod1 and changeIndexDynamicArrayMethod1 you are not passing an array there is no pass by reference (which only happens if the parameter type is a reference type -- i.e. with &). The parameter has type int * (pointer to int). You are passing a pointer to int by value. There is no "dereference operator" in either function.
ne is already an int *, so passing it is nothing special. arr is an int [3], an array, not a pointer. In C, when an array-of-T is used in a context that expects a pointer-to-T, it is implicitly converted (without you needing to do anything) to a pointer to its first element. So when you do, changeIndexStaticArrayMethod1(arr), the compiler gets a pointer to the first element of arr, and passes that to the function.
The [] operator works on pointers. a[i] is always guaranteed to be the same as *(a + i). Inside both the changeIndexStaticArrayMethod1 and changeIndexDynamicArrayMethod1 functions, [] is used to access subsequent elements using a pointer to the first element.

Why i can't watch the expression a[1][1] after declare it by a[n][n] in c++?

my code:
#include <iostream>
using namespace std;
int main() {
int n=5;
int a[n][n];
a[1][1]=5;
return 0;
}
I got this error when trying to watch the expression a[1][1] in eclipse on line 6:
Failed to execute MI command:
-data-evaluate-expression a[1][1] Error message from debugger back end:
Cannot perform pointer math on
incomplete types, try casting to a
known type, or void *.
i guess it's returned from gdb? however, i don't know why i can't watch that value? Isn't "a" is a normal multi-dimensional array?
For some odd reasons this isn't valid C++ unless you make it
const int n = 5;
Otherwise the array size is formally unknown until runtime.
C++ doesn't suppose variable length array (VLA). So your code is not standard conformant code.
It will not compile if you compile it with g++ -pedantic. The array size must be constant expression. But in your code, its not.
So write:
const int n=5; //now this becomes constant!
int a[n][n]; //the size should be constant expression.
Lets try the above code, as its completely Standard conformant code now.
why not better do it a dynamic 2d array? In that case you do not have to make the n constant, and you can determine the size dynamically.
int **arr, n;
arr = new int * [n]; // allocate the 1st dimension. each location will hole one array
for (i=0; i<n; i++)
{
arr[i] = new int [n]; // allocate the 2nd dimension of one single n element array
// and assign it to the above allocated locations.
}
Now you can access the aray as arr[i][j]
To free to the reverse
for (i=0; i<n; i++)
{
delete [] arr[i]; // first delete all the 2nd dimenstion (arr[i])
}
delete [] arr; // then delete the location arays which held the address of the above (arr)