-3

I have problem while initializing char array(in constructor) in dynamic zone of memory. How can i initialize a dynamic allocated memory type char*

class Funkcija
{
protected:
    float k;
    float n;
    char* naziv;

#include "Funkcija.h"
#include <iostream>
using namespace std;
Funkcija::Funkcija()
{
    k = 1;
    n = 0;
    naziv = new char;
    naziv = 'Name';
    
}

1 Answers1

2

You are not allocating enough memory for a string "Name" (note the double quotes). You are allocating only 1 char, and 'Name' (single quotes) is a multi-byte character that will not fit in a single char.

You need something more like this instead (see the Rule of 3/5/0):

class Funkcija
{
protected:
    float k;
    float n;
    char* naziv;

public:
    Funkcija();
    Funkcija(const Funkcija &);
    ~Funkcija();

    Funkcija& operator=(const Funkcija &);
};
#include "Funkcija.h"
#include <algorithm>
#include <cstring>

Funkcija::Funkcija()
{
    k = 1;
    n = 0;
    naziv = new char[5];
    std::strcpy(naziv, "Name");
}

Funkcija::Funkcija(const Funkcija &src)
{
    k = src.k;
    n = src.n;
    naziv = new char[std::strlen(src.naziv)+1];
    std::strcpy(naziv, src.naziv);
}

Funkcija::~Funkcija()
{
    delete[] naziv;
}

Funkcija& Funkcija::operator=(const Funkcija &rhs)
{
    if (&rhs != this)
    {
        Funkcija temp(rhs);
        std::swap(k, temp.k);
        std::swap(n, temp.n);
        std::swap(naziv, temp.naziv);
    }
    return *this;
}

That being said, you really should be using std::string instead of char*, let the compiler handle all of these details for you, eg:

#include <string>

class Funkcija
{
protected:
    float k;
    float n;
    std::string naziv;

public:
    Funkcija();
};
#include "Funkcija.h"

Funkcija::Funkcija()
{
    k = 1;
    n = 0;
    naziv = "Name";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770