0

I am writing a function that takes in a string through pass by reference and an array of characters and the size of the array. The string already has characters in it. I am trying to erase the characters in the string and copy the characters from the array. I tried setting up a for loop to copy, but it doesn't work if the string is too small or too big. I can't use strcopy in this function. Need some guidance.

void functionname(string &first, char arr[], int size) {

int i;

    (for i = 0; i < size; i++) {
    first[i] = arr[i];
    }

}
2
  • 2
    What doesn't work about it? Are you getting errors? What are they? Commented Oct 30, 2014 at 2:42
  • FWIW, you code isn't reliable when the incoming value of first has .size() less than the size argument. Say first is "abc", arr[] is VWXYZ and size is 5... you copy VWX over abc - which is allowed - but then try to copy Z over the first[4] which is (as of C++11) guaranteed to hold a NUL but isn't legal to write to (for C++03 it may not be a NUL and is also undefined behaviour to write), then of course writing the final Z is beyond even any possible NUL and even in C++11 the indexing operation is undefined behaviour, let alone the write.... Commented Oct 30, 2014 at 3:13

4 Answers 4

2

You can use std::string's default assignment operator = and simply do

first = arr;
Sign up to request clarification or add additional context in comments.

1 Comment

just a note: this works if arr holds ASCIIZ text (i.e. textual character terminated by a NUL/0 character that you don't consider part of the text/value), while zzz777's answer happily sets the string to contain the first size characters from the array even if some/all are NUL.
2

std::string has function to do it first.assign(arr, size)

Comments

1

The below works as std::string overrides the assignment operator (=) for char* to allow direct assignment to the string from a character pointer.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

void functionname(string &first, char arr[], int size) 
{
    first = arr;
}

int main()
{
    std::string x = "mystring";
    char buff[x.length()];
    strcpy(buff, "other");

    cout << x << endl;
    functionname(x, buff, x.length());

    cout << x << endl;

    return 0;
}

Comments

0

string has a constructor that copies a character array and takes a count. This will work no matter what contents are inside the arr array, even embedded null characters.

void functionname(string &first, char arr[], int size) {

    first = string(arr, size);

}

Again, the contents of arr are copied into the string, you don't need to keep arr around after this if you don't need it anymore.

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.