C++ char* array

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?

Upvotes: 3

Views: 59714

Answers (5)

Artem Volkhin
Artem Volkhin

Reputation: 1372

This code might be helpful:

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

Upvotes: 1

Cubbi
Cubbi

Reputation: 47438

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';
}

Upvotes: 8

Robᵩ
Robᵩ

Reputation: 168626

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.

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137820

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.

Upvotes: 2

Juliano
Juliano

Reputation: 811

You have to initialize the variable t

Do something like this:

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

// strlen(t) = 0

Upvotes: 0

Related Questions