3

When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

0

5 Answers 5

8

Both strcpy and strlen expect to find the special character NUL or '\0' in the array. An uninitialized array, as the one you've created, may contain anything at all, which means the behavior of your program is undefined when it is passed to strcpy as the source argument.

Assuming the goal was to copy s into t, to make the program behave as expected, try this:

#include <iostream>
#include <cstring>
int main()
{
    const char* s = "test string";
    char* t = new char[44];
//  std::strcpy(t, s); // t is the destination, s is the source!
    std::strncpy(t, s, 44); // you know the size of the target, use it
    std::cout << "length of the C-string in t is " << std::strlen(t) << '\n';
    delete[] t;
}

But keep in mind that in C++, strings are handled as objects of type std::string.

#include <iostream>
#include <string>
int main()
{
    const std::string s = "test string";
    std::string t = s;
    std::cout << "length of the string in t is " << t.size() << '\n';
}
Sign up to request clarification or add additional context in comments.

Comments

2

What are you trying to do? Do you want to copy from s to t? If so, the arguments to strcpy are reversed.

char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it

Such C-style string processing is a red flag, but that's all I can say given this little information.

Comments

1

This code might be helpful:

char * strcpy (char * destination, const char * source);
t = strcpy(t, s);

Comments

0

You have to initialize the variable t

Do something like this:

char *t = new char[44];
memset(t, 0, 44);

// strlen(t) = 0

1 Comment

Or by using char* t = new char[44]();, you can get rid of the memset.
0

The strcpy function is described thus:

#include <string.h>
char *strcpy(char *dest, const char *src);

The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest.

So, if you are trying to fill in your newly allocated array, you should be doing:

strcpy(t, s);

Not the other way around.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.