0

When I'm trying to access classes public variable (in this case trying to input text row) it shows that it's uninitialized. However, I declared it in class as a public variable. I know that's some dummy mistake, but can't find it :D

#include <iostream>
#include <conio.h>

using namespace std;

class stringlength {
private:
    int lengt;
public:
    char * row;

    int len()
    {
        for (int i = 0, lengt = 0; (*(row + i) != '\0'); i++, lengt++) {}
        return lengt;
    }
};
int main()
{
    stringlength test;

    cout << "Enter a string:";
    cin >> test.row;
    cout << "Length is: " << test.len();
    _getch();

}

This program is expected to give a length of the inputted row (like strlen function) Error is:

Error C4700 uninitialized local variable 'test' used

Thanks for help ;)

Claudio
  • 10,614
  • 4
  • 31
  • 71
Raicha
  • 120
  • 8
  • 3
    Not only do you need to initialise `row`, you also need to allocate some memory to store the string in. Have a look at the [list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 18 '19 at 07:08
  • 3
    Naive question, why don't you use a `std::string` ? It's easier to use and harder to miss use. And it's have a `.size()` – Martin Morterol Apr 18 '19 at 07:23
  • As @molbdnilo say, you need to initialise `row` . https://stackoverflow.com/questions/15319690/char-and-cin-in-c may help – Martin Morterol Apr 18 '19 at 07:30
  • Take a look at https://stackoverflow.com/questions/15131772/assigning-cin-to-variables – eMazarakis Apr 18 '19 at 08:44
  • std::string is easy. Yep :D But the task is about using a pointers to find the length – Raicha Apr 18 '19 at 09:16

1 Answers1

3

Declaring the variable does not mean that it's initialized.

Initialize it in a constructor, or just char * row = nullptr; (if 0 is the intended initialization).

Same for all the variables that you have which have no constructors.

Edit: in this specific case you need to initialize to a new pointer char * row = new char[...]

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78