Search code examples
c++referencedynamic-arrays

How to modify array inside function which doesn't take this array as parameter


What I need is to modify pTab array inside modifyAA(int a) function. How can I achieve this?

Example Code:

int modifyAA(int a); 

int main()
{
  *pTab=new int[10]; int a=13;

  for(int i=0;i<=9;i++)
      pTab[i]=88;                      

  modifyAA(a);      
  //I'd like to have pTab to be modified after function invoke
return 0;
}

modifyAA(int a){

  for(int i=0;i<=9;i++)
     pTab[i]=pTab[i]+1; 

a=a+pTab[0];  
return a;                  
};       

Is it possible to modify array when function doesn't take it as parameter ?


Solution

  • You can use a global variable for the pointer to the first element of the dynamic array:

    int * pTab;
    
    int printAA(int a)
    {
        for (unsigned int i = 0 i != 10; ++i)
        {
            ++pTab[i];
        }
        return a + pTab[0];
    }
    
    int main()
    {
        pTab = new int[10];
    
        // populate
    
        printAA(13);
    }