简体   繁体   中英

visual studio c++ empty string pointers

I have written some code with string pointers in VS2013 c++, as follows:

      public struct MyStruct
          {  // some declarations
             string *MyStrAr[6];
          };
          // ... some more code
      MyStruct *AStructNode = new MyStruct;

the user gives input that initialises some strands of the Mystringarray and assigns a value to them. Further in the program, I want to check if Mystringarray[i] has been initialised. I have tried the following:

if (AStructNode->MyStrAr[i]==NULL)
if (AStructNode->MyStrAr[i]->empty())
if(*(AStructNode->MyStrAr[i])="")
if (AStructNode->MyStrAr[i]->_Mysize==); 

the first doesnt capture anything (whether the string is populated or not), the rest throw an exception about trying to access protected memory. I have also tried try { } catch(...) {}, also unsuccessfully. Have read as many posts on the matter before posting this, I am amateur programmer, any help/direction appreciated. (I realise, I can sidestep the issue by, for example, declaring an array of strings rather than pointers, but I'd rather understand why, and if my oversight is very elementary, so be it!). If of any help, the debugger usually throws the exception on a line of the xstring.cpp, where it says something like return (this->_Mysize == 0); Cheers, Niko

AStructNode->MyStrAr[i]==NULL

You have not initizlized MyStrAr[i] so it might not be NULL.

AStructNode->MyStrAr[i]->empty()

Dereferencing uninitialized pointer has undefined behaviour.

*(AStructNode->MyStrAr[i])=""

Same as above. Comparing to const char* literal (I'm assuming you don't actually mean to use assignement) won't work either.

AStructNode->MyStrAr[i]->_Mysize==

Same as the above two.

You cannot test if value is uninitialized. In fact you shouldn't read such memory at all. Initialize your values with say, NULL. Then your first test AStructNode->MyStrAr[i]==NULL should work as long as i <= 5 . For the other tests to work, you would need to construct the strings pointed by MyStrAr too because dereferencing a NULL pointer has undefined behaviour.

public struct MyStruct
{
    string *MyStrAr[6] = {NULL};
};

If your compiler does not support brace initialization, you need to use a constructor:

public struct MyStruct
{
    string *MyStrAr[6];

    MyStruct(): MyStrAr() {}
};

A sidenote: Does MyStrAr absolutely must be ac style array? std::array has many advantages. std::vector is good too if your compiler does not support c++11.

the parameter _Mysize is private for the String class so you dont have permission to use that! try this instead:

if (AStructNode->MyStrAr[i]->size()==...(some number));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM