Hi,
I want to make a global 2D array ( i mean outside of the main function), so it will be available from all the functions.
But my problem is how can i read it's size from the keyboard?
If anyone know, plz help me.

Thanks in advance.

if u want 2 create a static array, u have make the array dimension known at the compile time. so u have no option to take the size from user.

his is only possible by means of dynamic array.

u may be needing sth like this....

#include <iostream>
using namespace std;

int *arr[2];

int main() {
    int x;
    cout<<"Enter size of each 1D array : ";
    cin>>x;
    arr[0]= new int[x];
    arr[1]= new int[x];

    arr[0][2]=100;
    cout<<arr[0][2]<<endl;

    //at the end
    delete[] arr[0];
    delete[] arr[1];
    return 0;
}

Or attempt a design where it is created in main() and passed into the functions that require it.

I have concerns related to this (it's probably nothing though):

//at the end
    delete[] arr[0];
    delete[] arr[1];

I'm not too sure it will work correctly.

Reason:
Since an array technically is just a pointer to the first element of the array, won't you lose access to your whole array if you do delete[] arr[0]; first? Shouldn't you delete[] arr[1]; first so that you don't lose your pointer? Or am I missing something?

EDIT:
Wait a minute. I was thinking on it more. Will these lines just clear the contents of arr[0] and arr[1] and not touch arr itself?

Edited 6 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.