-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 ???

5
  • 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. Commented Jul 12, 2020 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. Commented Jul 12, 2020 at 23:15
  • strncpy(c, s.c_str(), 50); followed by c[49] = '\0'; for robustness Commented Jul 12, 2020 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*. Commented Jul 13, 2020 at 1:42
  • Does this answer your question? How to copy a string into a char array in C++ without going over the buffer Commented Jul 13, 2020 at 1:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't null-terminate the destination char array.
This may cause nasty errrors, if the input strings are longer than the buffers.
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));

Comments

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).

2 Comments

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.
Or a std::string_view for that matter

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.