Hello, i'm reviewing the exercise from the book and trying to understand the point. Basically it creates a static array and declares uninitialized char pointer. Then it allocated memory dynamically to the same char pointer. What i don't understand why is the program using strcpy() to copy string into newly allocated location instead of just setting a pointer to that memory address. Unless the author just intended to illustrate that theres a function that can do just that. Here's the snippet of what i mean. Thanks for the help.

char monster[4] = {'f','o','x'};

	char *p = new char[strlen(monster) + 1];

	cout << monster << ":" << &monster;

	//p = monster;

	strcpy(p,monster); // why not just assign memory location to p ?

	cout << endl;
	cout << p << ":  " << &p;

	//delete []p; // can't delocate memory ?

>>why not just assign memory location to p ?

Because the intent of the exercise is to show you how to make a duplicate copy of the original.

>>why not just assign memory location to p ?

Because the intent of the exercise is to show you how to make a duplicate copy of the original.

Yes after starring at it for a while i understood. Also if i just assign to pointer p location of monster i lose the newly allocated space. Thanks

Also i guess the reason for me not being able to use delocate mmemory is because pointer p now points to animal array address which was not created dynamically using keyword new and therefore can't be freed. Am i thinking along the right lines?

Edited 5 Years Ago by Crutoy: Additional

>>i lose the newly allocated space.
Exactly. If you set p = monster, you will lose access to the memory that was allocated before. But worse, you can no longer delete the memory you had allocated before (because you no longer have the address to it), this is called a memory leak!

Thanks, i guess i was typing as you posted. Very thankful for explanation.

Yes you are right the memory which is allocated dynamically can only be destroyed or deallocated using the delete keyword

This article has been dead for over six months. Start a new discussion instead.