how to access array outside its scope

This is a discussion on how to access array outside its scope within the C++ Programming forums, part of the General Programming Boards category; here is a sample pseudo code of what i want to perform( i am using dev c++) Code: main() { ...

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    25

    how to access array outside its scope

    here is a sample pseudo code of what i want to perform( i am using dev c++)
    Code:
     main()
    {
      int r,c;
      cin>>r>>c;
      
      int a[r][c];
    }
    
    void f1()
    {
      ....
      ....
    }
    i want to access array a inside f1(). i can't pass array a as argument because then in the function prototype of f1 it will have to be of fixed size (like a[5][5]). so is there a way to access a inside other blocks. i tried :: operator but it won't work.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,633
    No, the :: (scoping) operator cannot be used as you describe.

    Your creation of the array a is illegal in C++, anyway, so it's a moot point that you can't access it directly from f1(). And main() returns int.

    In C++, I'd use this (assuming f1() does not intend to change the passed information);
    Code:
    #include <vector>
    #include <iostream>
    
    void f1(const std::vector<std::vector<int> > &);
    
    int main()
    {
         int r,c;
         std::cin >> r >> c;
    
         std::vector<std::vector<int> > a(r, std::vector<int>(c));
    
         f1( a);
    }
    
    void f1(const std::vector<std::vector<int> > &a)
    {
        //   use a here
    }
    This is legal, as vectors carry their size information with them .... and so do vectors of vectors.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array of pointers not changing out of scope?
    By LaffyTaffy in forum C++ Programming
    Replies: 1
    Last Post: 07-29-2010, 01:17 PM
  2. Array access
    By Kempelen in forum C Programming
    Replies: 7
    Last Post: 05-06-2009, 06:22 AM
  3. Access array from class
    By parad0x13 in forum C++ Programming
    Replies: 6
    Last Post: 03-18-2009, 09:12 AM
  4. Access Array
    By peacealida in forum C++ Programming
    Replies: 1
    Last Post: 04-02-2008, 01:13 AM
  5. Cannot access pointers from an array
    By Datamike in forum C++ Programming
    Replies: 4
    Last Post: 11-05-2005, 02:16 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21