Hello everybody!
I want to ask something that crossed my mind today about strcpy..I wrote the following piece of code and although i didn't expect it to work..it worked!

#include <iostream>

using namespace std;

int main() {
   char name[20], *dname;
   cout << "what's your name?: ";
   cin.getline(name, 20);

   strcpy(dname, name);
   cout << "your name is " << dname << endl;
   return 0;
}

I thought that the left parameter in strcpy had to be a pointer to an array that its size would be well known...Instead i passed as a parameter just a pointer to char and the example worked..So does it have to be just a pointer? And another thing..if i replace the array "name[20]" with a pointer to char "*name" getline doesn't work..
Thank you in advance for reading my post!

Recommended Answers

All 3 Replies

Let's just say you're lucky it worked. Technically, what you have written is accurate syntax, but it is logically incorrect and very dangerous code.

Because it's simply a pointer to a single char, there is not sufficient memory allocated where that char is stored to hold an array of char. Your program should have crashed with a segmentation fault. The only possible reason it didn't is because your input wasn't large enough to corrupt any memory that wasn't dedicated to your program.

Let's just say you're lucky it worked. Technically, what you have written is accurate syntax, but it is logically incorrect and very dangerous code.

Because it's simply a pointer to a single char, there is not sufficient memory allocated where that char is stored to hold an array of char. Your program should have crashed with a segmentation fault. The only possible reason it didn't is because your input wasn't large enough to corrupt any memory that wasn't dedicated to your program.

So when i'm willing to use a pointer to char with functions such as strcpy, i have to initialize the pointer with a specific allocated memory...am i right? Is this a general rule? I mean, let's say that a private member of a class i've written is a char pointer. If i want to initialize my pointer (via a constructor maybe), then i need to specify how much memory will be allocated from my pointer in order to use strcpy (or a relative function..)?? Thank you again for your instant reply..

Because it's simply a pointer to a single char, there is not sufficient memory allocated where that char is stored to hold an array of char.

Actually, there isn't even a single char. It's just a pointer to nowhere in particular.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.