-1

is there any way to copy from char* to char[] other than using strcpy? I tried this and does not work.. for ex

char* t1 = "hello";
char t2[6];
t2 = t1;

It is not compiling.. saying that incompatible types of assignment of 'char*' to char[6]

Thank you

in His Steps
  • 3,075
  • 6
  • 30
  • 38

6 Answers6

3

Use strncpy:

strncpy(t2, t1, 6);
abelenky
  • 63,815
  • 23
  • 109
  • 159
2

First thing first - you cannot do char* t1 = "hello";; Simply because string literals are constant, and any attempt to modify them trough t1 will result in undefined behavior.

Since C++ doesn't have assignment operators from constant character pointer to character array, you have to copy memory manually. memcpy, memmove, strcpy or strncpy are your standard options, and you can always write your own (which I don't recommend you doing).

1

You need strcpy. Arrays in C++ (an C) have a pointer to the first item (character in this case).

So strcpy(t2, t1) will do the trick.

Also - being perdantic you need const char * const t1 = "hello" - but the standard gives a lot of tolerance on that subject.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

In C++, you can also use copy:

#include <algorithm>

std::copy(t1, t1 + 6, t2);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @MichaelDorgan: You can use `std::min((sizeof t2) - 1, std::strlen(t1))` if you prefer and add a trailing zero manually. – Kerrek SB Nov 25 '11 at 17:45
  • No. Use the functions designed for this: strncpy(). We already know that the C-String handling feature are inherently unsafe and thus you take a closer look at features that use/see them. using std::copy() sort of gives it an air of acceptability that makes you worry less. I would prefer to worry more that the author is using unsafe techniques so I can convert to std::string quicker. – Martin York Nov 25 '11 at 19:52
  • @LokiAstari: The OP said explicitly "other than strcpy". I assumed that "strncpy" was subsumed in that condition. – Kerrek SB Nov 25 '11 at 19:54
1

To be supersafe, you should use strncpy to copy and strnlen to get the length of the string, bounded by some MAX_LENGTH to protect from buffer overflow.

char t2[MAX_LENGTH];
strncpy(t2, t1, strnlen(t1, MAX_LENGTH))

Remember, that t1 is only a pointer - a number that points you to some place in memory, not an actual string. You can't copy it using assignment operator.

Piotr Zierhoffer
  • 5,005
  • 1
  • 38
  • 59
0
char* t1 = "hello";
char t2[6];
memcpy(t2, t1, 6);

Or

char* t1 = "hello";
char t2[6] = { t1[0], t1[1], t1[2], t1[3], t1[4], t1[5] };
TVOHM
  • 2,740
  • 1
  • 19
  • 29
  • I understand it is not the point of the question, but beware multibyte characters in string literals when assessing that, say, "hello" is 6 bytes long. – phs Jul 28 '12 at 19:28