Here is the exercise I am trying to complete:
I have a basic understanding of pointers, but I'm totally new to dynamic memory, so I really had no idea what to do with this one. Here's my failing code:Write a function that takes a char* argument. Using new,
dynamically allocate an array of char that is the size of
the char array that’s passed to the function. Using array
indexing, copy the characters from the argument to the
dynamically allocated array (don’t forget the null
terminator) and return the pointer to the copy. In your
main( ), test the function by passing a static quoted
character array, then take the result of that and pass it
back into the function. Print both strings and both
pointers so you can see they are different storage. Using
delete, clean up all the dynamic storage.
There are two issues with this code. 1) I don't know how to find the size of the array, so the function has to be given the length of the array. How can I find an array's size?Code:#include <iostream> using namespace std; char dynChar(char* a, int size){ char* b = new char[size]; for (int i=0; i<size; i++) b[i] = a[i]; return *b; delete[] b; } int main(){ char c[] = "Hello world!"; char d[] = dynChar(c,13); //line 14, with the error cout << d; return 0; }
2) It won't compile. It gives an error at line 14, saying the initializer can't determine the size of d. I don't really know what that means. Could someone help me out with this?