V
V
Vladislav2016-01-04 09:00:18
C++ / C#
Vladislav, 2016-01-04 09:00:18

How to write an analogue of the strcpy() function with memory allocation?

According to the task, you need to write a function, copying a string, into a new string with memory allocation. Why should it be allocated in this function?
Unfortunately, according to the code, nothing comes to mind. Google also gives inappropriate options.
This ... works, but to me, it's an unfortunate option.

char *str1 = "123456789112345";
    char *str2 = "sdf";
    str1 = str2;
    cout << str1 << endl;
    cout << str2 << endl;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Tsilyurik, 2016-01-04
@OnlyBooid

you need to write a function, copying a string, to a new string with memory allocation

This is the POSIX strdup() function.
You can see how it works.
Something like this:
char* strdup( const char *s ) {
   char *p = malloc( strlen( s ) + 1 );
   if( p ) strcpy( p, s );
   return p;
}

A
Armenian Radio, 2016-01-04
@gbg

If you are using iostreams, work with std::string. If a teacher is interfering with C and C++ in front of the students, tell him he's weird.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question