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 ;)

5
  • 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. Commented Apr 18, 2019 at 7: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() Commented Apr 18, 2019 at 7:23
  • As @molbdnilo say, you need to initialise row . stackoverflow.com/questions/15319690/char-and-cin-in-c may help Commented Apr 18, 2019 at 7:30
  • Take a look at stackoverflow.com/questions/15131772/assigning-cin-to-variables Commented Apr 18, 2019 at 8:44
  • std::string is easy. Yep :D But the task is about using a pointers to find the length Commented Apr 18, 2019 at 9:16

1 Answer 1

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[...]

Sign up to request clarification or add additional context in comments.

2 Comments

But I'm inputting it through cin. It seems a bit strange to me.
Initialising it as array helped. ``` char * row = new row [4096] ```

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.