-1

in c++ suppose I have:

string s[] = {"red","green","blue"} ;
char c[50] ;

I wanna make an assignment like this:

c = s[0] ;

how can I do it ???

  • `char c[50]` is not a pointer type, btw - think of it as the same thing as putting `char c0, c1, c2, c3, c4` - so you'll need to copy the `string`'s characters into `c` rather than merely assigning a pointer/reference **or** change `char c[50]` to a pointer or reference to a heap-allocated array. – Dai Jul 12 '20 at 23:15
  • That said, if you want to write C++ and not C, then use STL types like `std::vector` and `std::array` and avoid raw pointers and raw arrays. – Dai Jul 12 '20 at 23:15
  • `strncpy(c, s.c_str(), 50);` followed by `c[49] = '\0';` for robustness – selbie Jul 12 '20 at 23:38
  • As an aside, often you can make do with the c_str() function, for example if a legacy function expects a const char*. – Peter - Reinstate Monica Jul 13 '20 at 01:42
  • Does this answer your question? [How to copy a string into a char array in C++ without going over the buffer](https://stackoverflow.com/questions/2889421/how-to-copy-a-string-into-a-char-array-in-c-without-going-over-the-buffer) – Andreas is moving to Codidact Jul 13 '20 at 01:45

3 Answers3

0

For whatever the purpose, consider if you can use std::string instead of a char array (re. array c).

If you still want to do it, you can use strcpy or memcpy:

const char *cstr = s[0].c_str();
size_t len = strlen(cstr);
size_t len_to_copy = len > sizeof c ? sizeof c : len;

memcpy(c, cstr, len_to_copy - 1);
c[len_to_copy - 1] = 0; 

(Copying a byte less & terminating with null byte isn't necessary if 'c' doesn't need to be a C-string).

Note that this could truncate if c doesn't have any space. Perhaps std::vector<char> is better suited (depends on the use-case of course).

P.P
  • 117,907
  • 20
  • 175
  • 238
  • If the string is shorter than the array, it won't be null-terminated properly. Also you can copy one character less than `sizeof c`, if you're going to overwrite the last one with `0`. – HolyBlackCat Jul 12 '20 at 23:31
  • Or a `std::string_view` for that matter – sehe Jul 12 '20 at 23:37
0

I would use std::copy

#include <iostream>
#include <string>

int main()
{
  std::string strings[] = {"string", "string2"};
  char s[10];
  std::copy(strings[0].begin(), strings[0].end(), s);
  std::cout << s; // outputs string
}

The advantage of using std::copy is its use of iterators.

BidoTeima
  • 490
  • 1
  • 4
  • 13
0

I would use std::strncpy. It will zero terminate your buffer and wont write out of bounds.

char c[50];
std::string test_string = "maybe longer than 50 chars";
std::strncpy(c, test_string.c_str(), sizeof(c));
OutOfBound
  • 1,914
  • 14
  • 31