473,399 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Scope of Dynamically Allocated Arrays in class member functions

emaghero
I have the following class declaration
Expand|Select|Wrap|Line Numbers
  1. class class_name{
  2. public:
  3.    class_name(); // Constructor
  4.  
  5. // Member functions
  6.    void function_1();
  7.    void function_2(double *mat);
  8.    void function_3();
  9.  
  10.    void function_2_re_def(double *mat);
  11.    void function_3_re_def();
  12.  
  13. public:
  14.    int rows;
  15.    int cols;
  16.  
  17.    double *v1;
  18.    double *v2;
  19. };
  20.  
The member functions, function_1 and function_2, perform the same task. They store some computed data in the array. I define function_1 as follows
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_1()
  2. {
  3.    v1=new(double[(rows+1)*(cols+1)]);
  4.  
  5.    double some_number;
  6.  
  7.    for(int i=1;i<=rows;i++){
  8.       for(int j=1;j<=cols;j++){
  9.          *(v1+i*(cols+1)+j)=some_number;
  10.       }
  11.    }
  12. }
  13.  
I define function_2 as
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_2(double *mat)
  2. {
  3.    mat=new(double[(rows+1)*(cols+1)]);
  4.  
  5.    double some_number;
  6.  
  7.    for(int i=1;i<=rows;i++){
  8.       for(int j=1;j<=cols;j++){
  9.          *(mat+i*(cols+1)+j)=some_number;
  10.       }
  11.    }
  12. }
  13.  
The only difference is that I want to pass an array to the function that does the same task instead of being limited as I am in function_1 which will only allow the operation to be performed on a single array. I want to be able to call function_1 or function_2 inside another function to do something else with the computed data. If I use function_1 inside this other function, called function_3, no problems arise.
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_3()
  2. {
  3.    // perform the computation, 
  4.    function_1();
  5.  
  6.    // The data in v1 can be accessed inside this function
  7.  
  8.    // Print the data to screen
  9.    for(int i=1;i<=rows;i++){
  10.       for(int j=1;j<=cols;j++)
  11.          cout<<*(v1+i*(cols+1)+j)<<" ";
  12.       cout<<endl;
  13.    }
  14. }
  15.  
However, I cannot get this to work if I use function_2, i.e. if I define function_3 as
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_3()
  2. {
  3.    // perform the computation, 
  4.    function_2(v2);
  5.  
  6.    // The data in v2 cannot be accessed inside this function
  7.  
  8.    // Print the data to screen fails, program crashes
  9.    for(int i=1;i<=rows;i++){
  10.       for(int j=1;j<=cols;j++)
  11.          cout<<*(v2+i*(cols+1)+j)<<" ";
  12.       cout<<endl;
  13.    }
  14. }
  15.  
What is more infuriating is that if I redefine function 2 by removing the call to new
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_2_re_def(double *mat)
  2. {
  3.    double some_number;
  4.  
  5.    for(int i=1;i<=rows;i++){
  6.       for(int j=1;j<=cols;j++){
  7.          *(mat+i*(cols+1)+j)=some_number;
  8.       }
  9.    }
  10. }
  11.  
and redefine function_3 as
Expand|Select|Wrap|Line Numbers
  1. void class_name::function_3_re_def()
  2. {
  3.    // perform the computation, 
  4.    v2=new(double[(rows+1)*(cols+1)]);
  5.    function_2(v2);
  6.  
  7.    // The data in v2 can now be accessed inside this function
  8.  
  9.    // Print the data to screen 
  10.    for(int i=1;i<=rows;i++){
  11.       for(int j=1;j<=cols;j++)
  12.          cout<<*(v2+i*(cols+1)+j)<<" ";
  13.       cout<<endl;
  14.    }
  15. }
  16.  
The program doesn't crash. I would like to know why the first version of function_3 with the call to function_2 crashes when called and why the second version, function_3_re_def with the dynamic memory allocation before the call to function_2_re_def, doesn't.

Is there a scope issue that means that you must know the size of an array before passing arrays into class member functions?

Thanks for your help.
Sep 16 '10 #1
5 1868
weaknessforcats
9,208 Expert Mod 8TB
This code:

Expand|Select|Wrap|Line Numbers
  1. void class_name::function_2(double *mat) 
  2.    mat=new(double[(rows+1)*(cols+1)]); 
  3. etc...
doesn't do what you think.

mat is a local variable. It dies when the function completes. That is, mat is a copy of the original pointer.

Now if you need to change the address inside the original pointer and have that change visible in other functions, then you will need to pass the address of the original pointer:

Expand|Select|Wrap|Line Numbers
  1. void class_name::function_2(double **mat) 
  2.    *mat=new(double[(rows+1)*(cols+1)]); 
Sep 16 '10 #2
Oralloy
988 Expert 512MB
At the risk of being cheeky, how about passing as a reference to a pointer?

Expand|Select|Wrap|Line Numbers
  1. void class_name::function_2(double *&mat)
  2. {
  3.   mat = new double[(rows+1)*(cols+1)]
Then you can have happily confusing code that transparently assigns the outer pointer value.

BTW, this sort of memory management is interesting, but I would think that STL vectors are a much better choice in most instances.
Sep 16 '10 #3
weaknessforcats
9,208 Expert Mod 8TB
You may pass a reference to a pointer.

What you save is making the copy of the pointer. However, underneath, the compiler implements a reference by using a pointer. That means you save nothing using a reference to a pointer.

What you should be using is a handle. Once you have allocated memory and pass that pointer around, you can't tell when it's safe to delete the allocation. It would only be safe if the pointer was the last copy in the program.

To keep track of the number of copies of the pointer you would need to implement reference counting.

You might read the C/C++ Insights article on using handle classes.
Sep 16 '10 #4
Oralloy
988 Expert 512MB
Yep.

I'm really unsure of what emaghero is trying to achieve.

If he wants reference counted dynamic arrays, he'll need to implement envelopes and include a reference count in the core object. Not difficult, actually, just tedious.

@emaghero - what is it you actully are trying to achieve?
Sep 16 '10 #5
Thanks for the replies.
Sep 19 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: qazmlp | last post by:
Does static member function of a class have 'extern "C" linkage ? And what about non-static member functions ?
3
by: Randy Yates | last post by:
Hi, Is there a way to write a class member function that does not require an instantiation of the object to be invoked? For example, class MYCLASS { bool CheckIfMYCLASS(string &teststring);...
7
by: Srini | last post by:
Hello, Rules for inline functions say that they have to be defined in the same compilation unit as their declarations. For class member functions this means that the inline member functions must...
3
by: lovecreatesbeauty | last post by:
Predefined class member functions and inheritance How many member functions on earth can be provided (predefined) by standard-compliant compilers? Scott Meyers says that there are 6:...
5
by: tricard | last post by:
Good day all, I have created a two dimensional array (matrix for my purposes) whose size is dynamically allocated. (i.e. rowSize and colSize are both taken as input, then malloc() is used to...
3
by: cweisbrod | last post by:
Hi All, I realize I may be posting to the wrong group, but I can't help but think my problem is more related to C++ than Microsoft's particular C++ compiler. I've been migrating a large...
1
by: SneakyElf | last post by:
hi all, im super new with c++ (and no background in programming whatsoever!) i have a task to make functions to calculate total profit and the average number of things sold. data is read from a...
12
by: Andy Terrel | last post by:
Okay does anyone know how to decorate class member functions? The following code gives me an error: Traceback (most recent call last): File "decorators2.py", line 33, in <module> s.update()...
1
by: Wynner | last post by:
I'm an old Delphi programmer getting into the C++ world, and trying to wrap my head around this problem. I have multiple classes derived from a generic class that passes one of it's functions as a...
6
by: jthep | last post by:
Hi I'm trying to write a JNI for a linkedlist class I wrote in C++. Basically I have a header file with the class definition and a C++ file with the definition of the class member functions. I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.