How to use Dynamic Allocation in CLASS

Hey guys, can you please show me how to use Dynamic Allocation in Classes.
I only need it for reading names (chars).

So if I'd like to cin an array with dynamic allocation (be it from the MAIN function), accessing a PRIVATE member of the class, how should I do it ?!

To be more precise, I need to know how to use 'Dynamic Allocation of a char array'.

This is important to me, cause tomorrow I have an exam about C++.
Your help would be appreciated.
Last edited on
How to dynamically allocate a char array:

char* Array = new char[sizeOfArray];
In class we use something different.
something like
new char=(strcpy(n1,n2)+1)

..
That's some hideous (and non-compiling) mish-mash of array concatenation code. You've got your questions and answers all mixed up. What do you actually want to know?
I want to know how can I use dynamic alloc. in the way of the example I gave in the previous post.

I think we are not allowed to use sizeOf in this period of the exam. (the next one yes).

Dynamic alloc is allocating memory at runtime, using new. That's all it is. Anything else you do involving strcpy and all that is nothing to do with dynamic allocation.

How do you use the memory you get from dynamic allocation? The same way you use any array or pointer.

1
2
char* array = new char[10]; // dynamically allocate
array[3] = 'f'; // Using it 

Last edited on
I remember using it inside a constructor?
Maybe it wasn't strcpy, but firstly measuring the length of the char that is being passed in the constructor, and after thet, allocating a memory by "THE_LENGTH_OF_THE_PASSED_ARRAY+1(for the NULL terminator"

this makes more sense I think. can you please show me an example of that.
Last edited on
1
2
int lengthOfString = strlen(someCharPointer);
char* array = new char[lengthOfString +1];
that's it, one more;
can I use strlen directly in the new char [strlen(someCharPointer)+1]
Ok, I just found out that I can, here's an example:

1
2
3
4
5
6
      Actor(char* ac="",int a=0);
      {
                  name_actor=new char[strlen(ac)+1];
                  strcpy(name_actor,ac);
                  age=a;
      }


I sow something like Virtual ~actor(){delete [] name_actor;}
I remember it was used to delete a dynamic allocated memory after u done using it, can you please tell me how it works?
Last edited on
Topic archived. No new replies allowed.