C0UG3R
C0UG3R

Reputation: 25

Program stops working when class member function executes

I know there is something wrong with the class member functions because I comment everything in them out and the program will run fine but when I uncomment anything it stops working. The constructor runs fine as well.

Here is my CharArray.h file:

#ifndef CHARARRAY_H
#define CHARARRAY_H

class CharArray
{
private:
    char * pArray;
    int iSize;

public:
    CharArray(int size)
    {
        char *pArray = nullptr;
        iSize = size;
        pArray = new char[iSize];
        pArray = '\0';
    }

    void setItem (int loc, char ch);
    char getItem (int loc);

    ~CharArray()
    {
        delete [] pArray;
    }
};

#endif // CHARARRAY_H

Here is my member functions:

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include "CharArray.h"
using namespace std;

void CharArray::setItem (int loc, char ch)
{

    pArray[loc] = ch;

    cout << pArray[loc] << endl;

  return;
}

char CharArray::getItem (int loc)
{
  char c;

    c = pArray[loc];

  return c;
}

And here is my main file:

#include <iostream>
#include <iomanip>
#include "CharArray.h"
using namespace std;

int main()
{
    CharArray myChar (5);
    int size;
    char cstr[10] = "Drew";

    myChar.setItem(1, 'A');

    char c = myChar.getItem(5);
    cout << c << endl;

return 0;
}

Upvotes: 1

Views: 102

Answers (1)

Edward
Edward

Reputation: 7090

Your first problem is in the constructor:

CharArray(int size)
{
    char *pArray = nullptr;   // <-- unrelated to the pArray in the object!
    iSize = size;
    pArray = new char[iSize];
    pArray = '\0';            // <-- we just lost the handle to new array
}

That last line should instead be:

    *pArray = '\0';

Also, it would be better to use a more modern constructor style such as this:

CharArray(int size)
     : pArray(new char[size]),
       iSize(size)
{
    *pArray = '\0';
}

Upvotes: 4

Related Questions