in BufferArray::operator+, tempCharArray is a temporary buffer that will be destroyed when the function completes. There a basically two ways to handle this:

1/ allocate the temporary buffer with new[] in operator+, that way you'll make sure the buffer survives the call to operator+ but you'll either have a memory leak or require the caller to invoke delete[] later on, which is rather clumsy and error-prone

2/ or better yet, modify setBuffer so it does an internal copy of the buffer and add a call to delete[] in your own destructor :

BufferArray::~BufferArray() {
    delete[] buffer;
}

void BufferArray::setBuffer(char *otherBuffer) {
    buffer = new char[strlen(otherBuffer) + 1];
    strcpy(buffer, otherBuffer);
}

Note that you'll have to modify the constructor so it also copies the input buffer (otherwise you'll have an illegal call to delete[] when the object is destroyed), and then you may want to overload the copy-constructor and assignment operator to prevent shallow copy which would result in double-deleting the buffer.

In actual production code, you'd want to use a managed pointer of some sort to avoid doing the delete yourself (e.g. std::vector or boost::shared_array), but for homework the above solution should be fine.

On a side note, don't forget to add +1 when using strlen to determine the size of your buffer ;)

Answer from ZeRemz on Stack Overflow
🌐
Reddit
reddit.com › r/cpp_questions › setter methods for a char array
r/cpp_questions on Reddit: Setter methods for a char array
February 3, 2021 -

Hi all, I am trying to write a setter for a char array but getting into issues in the compilation side.

This char array of mine is used for ingesting in the name of a course.

In my header file, I have the following:

class Course
{
    public:
        Course(const char *name, unsigned credits);
        void GetUnitName() const;
        void SetUnitName(char* buf);
    private:
        char cName[10];
        int cCredits;
};

inline void Course::GetName() const
{
    cout << "Course name is: " << cName << endl;
}

inline void Course::SetName(char *input)
{
    cName = input;
}

I got the following error:

`error: incompatible types in assignment of 'char*' to 'char [10]'`

I tried several ways such as giving the defined size `char input[10]` however that fails badly too.

Can someone kindly guide me?

🌐
Sololearn
sololearn.com › en › Discuss › 1951230 › how-can-i-use-setters-and-getters-in-a-char-array-c
How Can I use setters and getters in a char array? c++ | Sololearn: Learn to code for FREE!
I'm so used to work with std::string, but, I'm not sure how to use a char array in the getters and setters; I have this little code: char name[10] // I think is the same as char* name void setName(char* n) { name = n; } // ERROR is not assignable. char* getName() const { return name; } Ass you can see, I'm not sure how to get and set the name properly, how can I solved this? ... You will have to use some of the built in functions for char strings like strcpy for setting: { strcpy(n, name); }
Discussions

get and set char * - C++ Forum
This is for an homework assignment ... headache for me., I just would like some insight on the implementation of setting and getting a dynamic char array in the below structure. I realize I need a setter and a getter method. Also the string being passed in. A c-string will be ... More on cplusplus.com
🌐 cplusplus.com
How do I write setters and getters for an array? (c++) - Stack Overflow
Im writing a class within c++, however I am not certain on how to create the setters and getters for the arrays (sorry for it being a basic question!) I am getting the following error: expected p... More on stackoverflow.com
🌐 stackoverflow.com
getter and setter for array type - C++ Forum
The first bug would be my userid is showing weird character instead of "A1234567" which I had define. I guess the problem is at the constructor coding line. Another help would be for the top 5 score. can anyone guide me along how can I display 5 top score of a player? i'm really bad at using array ... More on cplusplus.com
🌐 cplusplus.com
Accessor (Getter) function for a c string (character array)
This is supposed to work by booting ... array of BookData class objects from a delimited data file. I need these 'setter' / 'getter' functions for accessing and manipulating these values to add other functionality. I am going to be working on this for the rest of tonight and all tomorrow. So anyone that can give me any advice on this subject would be most helpful. That which doesn't kill you makes you stronger. ... 'const char *' is your ... More on gamedev.net
🌐 gamedev.net
6
June 23, 2010
Top answer
1 of 2
4

in BufferArray::operator+, tempCharArray is a temporary buffer that will be destroyed when the function completes. There a basically two ways to handle this:

1/ allocate the temporary buffer with new[] in operator+, that way you'll make sure the buffer survives the call to operator+ but you'll either have a memory leak or require the caller to invoke delete[] later on, which is rather clumsy and error-prone

2/ or better yet, modify setBuffer so it does an internal copy of the buffer and add a call to delete[] in your own destructor :

BufferArray::~BufferArray() {
    delete[] buffer;
}

void BufferArray::setBuffer(char *otherBuffer) {
    buffer = new char[strlen(otherBuffer) + 1];
    strcpy(buffer, otherBuffer);
}

Note that you'll have to modify the constructor so it also copies the input buffer (otherwise you'll have an illegal call to delete[] when the object is destroyed), and then you may want to overload the copy-constructor and assignment operator to prevent shallow copy which would result in double-deleting the buffer.

In actual production code, you'd want to use a managed pointer of some sort to avoid doing the delete yourself (e.g. std::vector or boost::shared_array), but for homework the above solution should be fine.

On a side note, don't forget to add +1 when using strlen to determine the size of your buffer ;)

2 of 2
1

You need to use new to create these char arrays, otherwise the temporaries (like tempBA) are destroyed when you exit the scope.

void BufferArray::SetBuffer(char* buf)
{
   buffer = new char[strlen(buf)+1]; //edit, my size param wasn't necessary
   strcpy(buffer,buf);
}
🌐
Cplusplus
cplusplus.com › forum › beginner › 152717
get and set char * - C++ Forum
This is for an homework assignment (due in two weeks) and this is just one tiny aspect of the entire project that has been a major headache for me., I just would like some insight on the implementation of setting and getting a dynamic char array in the below structure. I realize I need a setter and a getter method. Also the string being passed in. A c-string will be random in length, so assuming this would need an dynamic char array.
🌐
Cplusplus
cplusplus.com › forum › general › 111968
getter and setter for array type - C++ Forum
The first bug would be my userid is showing weird character instead of "A1234567" which I had define. I guess the problem is at the constructor coding line. Another help would be for the top 5 score. can anyone guide me along how can I display 5 top score of a player? i'm really bad at using array =\ I understand that under the private sector I should probably define int topFivescore[5]. but if I assign that I cant seems to get my program to run.
🌐
GameDev.net
gamedev.net › forums › topic › 574855-accessor-getter-function-for-a-c-string-character-array › 4666826
Accessor (Getter) function for a c string (character array) - For Beginners - GameDev.net
June 23, 2010 - 'const char *' is your friend (well, actually it's your worst enemy, but if that's what you need to use then so be it).There is a function called 'strncpy' which you should probably use.Getters which return char *s are generally a BAD IDEA with c-style strings. The common pattern in C is to use
🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 152877-char-array-getter.html
Char array getter
Since you posted on C++, the best thing to do is use std::string. But in C, the only useful way is to pass a pointer to a char array, where you want the answer to be stored, along with a length parameter. fgets() is a really good model for this style of interface.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › set-value-of-unsigned-char-array-in-c-during-runtime
Set value of unsigned char array in C during runtime - GeeksforGeeks
July 12, 2025 - // C program to set the value // of unsigned char array during runtime #include <stdio.h> #include <string.h> int main() { // Initial unsigned char array unsigned char arr[3] = { 0 }; // Print the initial array printf("Initial unsigned char array:\n"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%c ", arr[i]); } printf("\n"); // Using memcpy() to change the values // during runtime memcpy(arr, (unsigned char[]){ '1', '2', '3' }, sizeof arr); // Print the updated array printf("Updated unsigned char array:\n"); for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%c ", arr[i]); } printf("\n"); return 0; }
Top answer
1 of 1
8

I would say:

// student.h
class Student
{
public:
    // If you can, don't use numbers: 
    // you have a 3 on the variable,
    // a 3 on the function, etc.
    // Use a #define on C or a static const on C++
    static const int SIZE= 3;
    // You can also use it outside the class as Student::SIZE

public:
    void SetDaysToCompleteCourse(int* daysToCompleteCourse);

    // The consts are for "correctness"
    // const int* means "don't modify this data" (you have a setter for that)
    // the second const means: this function doesn't modify the student
    // whithout the const, student.GetDaysToCompleteCourse()[100]= 1 is 
    // "legal" C++ to the eyes of the compiler
    const int* GetDaysToCompleteCourse() const; // Ditto @ above comment.

    Student()
    {
        // Always initialize variables
        for (int i= 0; i < SIZE; i++) {
            daysToCompleteCourse[i]= 0;
        }
    }

private:
    int daysToCompleteCourse[SIZE];
    // On GCC, you can do
    //int daysToCompleteCourse[SIZE]{};
    // Which will allow you not to specify it on the constructor
};

// student.cpp
void Student::SetDaysToCompleteCourse(int* newDaysToCompleteCourse) 
{
    // It's not wrong, just that
    // this->daysToCompleteCourse[0] = daysToCompleteCourse[0];
    // use another name like newDaysToCompleteCourse and then you can suppress this->
    // And use a for loop
    for (int i= 0; i < SIZE; i++) {
        daysToCompleteCourse[i]= newDaysToCompleteCourse[i];
    }
}

const int* Student::GetDaysToCompleteCourse() const
{
    return daysToCompleteCourse;
}


// main.cpp
#include <iostream>

std::ostream& operator<<(std::ostream& stream, const Student& student)
{
    const int* toShow= student.GetDaysToCompleteCourse();
    for (int i= 0; i < Student::SIZE; i++) {
        stream << toShow[i] << ' ';
    }
    return stream;
}

int main()
{
    Student student;
    int daysToCompleteCourse[3] = { 1, 2, 3 };
    // You don't need this
    //int* ptr = daysToCompleteCourse;
    //student.SetDaysToCompleteCourse(ptr);
    //You can just do:
    student.SetDaysToCompleteCourse(daysToCompleteCourse);

    // On C++ int* is "a pointer to an int"
    // It doesn't specify how many of them
    // Arrays are represented just by the pointer to the first element
    // It's the FASTEST and CHEAPEST way... but you need the SIZE
    const int* toShow= student.GetDaysToCompleteCourse();
    for (int i= 0; i < Student::SIZE; i++) {
        std::cout << toShow[i] << ' ';
        // Also works:
        //std::cout << student.GetDaysToCompleteCourse()[i] << ' ';
    }
    std::cout << std::endl;

    // Or you can do: (because we defined operator<< for a ostream and a Student)
    std::cout << student << std::endl;
}

You can check out it live here: https://ideone.com/DeJ2Nt

🌐
Quora
quora.com › Can-we-assign-a-string-to-a-char-array-in-C
Can we assign a string to a char array in C? - Quora
Answer (1 of 8): You can do that in any language — take each character in the string and assign it to the next index in an array [character]. But don’t learn programming with C. It is a primitive, old, and flawed language and you will learn a lot of unimportant things and completely miss ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › how-to-initialize-char-array-in-struct-in-c
How to Initialize Char Array in Struct in C? - GeeksforGeeks
July 23, 2025 - When we create a structure instance (variable) in C that includes a char array, we can set an initial value for that char array directly using the list initialization.
🌐
Stack Overflow
stackoverflow.com › questions › 579734 › assigning-strings-to-arrays-of-characters
c - Assigning strings to arrays of characters - Stack Overflow
I am a little surprised by the following. Example 1: char s[100] = "abcd"; // declare and initialize - WORKS Example 2: char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_character_arrays.htm
Character Array in C
In C, characters and strings are stored differently. A character array stores a sequence of characters, like text. We use single quotes (' ') to define a single character (e.g., 'A') and double quotes (" ") to define a string or a character array
🌐
Delft Stack
delftstack.com › home › howto › initialize char array in c
How to Initialize Char Array in C | Delft Stack
February 2, 2024 - A char array is mostly declared as a fixed-sized structure and often initialized immediately. Curly braced list notation is one of the available methods to initialize the char array with constant values.
🌐
Quora
quora.com › How-can-I-declare-and-perform-assignment-to-an-array-of-characters-in-C
How to declare and perform assignment to an array of characters in C - Quora
Answer (1 of 3): I have been to a C/C++ technical interview, and it's worth mentioning the difference between two forms; char* s = “Hello, World!”; char s[14] = “Hello, World!”; The second one allows us to modify the string using indices as desired; s[6] = ‘x'; While the first one ...