So I'm pretty new to programming and had a quick question about the order in which you declare/instantiate in your code. I'll try and be as specific and clear as possible.
I understand the appropriate places to declare/instantiate in terms of scope. But I was trying to run a certain program and after successfully compiling it I received a runtime error of:
null pointer passed as argument 2, which is declared to never be null
I ran the debugger and noticed that a string I had declared but not yet assigned (call it string a
) became null randomly. So the program would crash when it went to use it in a loop.
However, I knew the only change I had made was that instead of hardcoding a particular variable with a value that the string used in its assignment nested in the proceeding loop (which by the way was hardcoded outside of int main
and ran fine), I instead instantiated a character array (let's call it char array b
) in int main
to allow for some variability given a user's input. This instantiation came in the line of code ABOVE the string's declaration (for no particular reason but just by chance). But both were in the same scope.
Before (WITH ERROR):
char array b[] = {};
string a;
If ()
{
for()
{
//string a = (equation containing char array b);
//returns value of string a;
};
};
After a lot of frustration I just happened to switch the order of the string declaration and the array instantiation and now my program runs fine.
Now (WITHOUT ERROR):
string a;
char array b[] = {};
If ()
{
for()
{
//string a = (equation containing char array b);
//returns value of string a;
};
};
I've been searching to see if declaration/instantiation order within the same scope matters when compiling but I can't seem to find a definitive answer. My gut tells me that because string a
ultimately depends on char array b
's value that I have to declare string a
first. But why would instantiating char array b
first automatically make string a
null if I'm not yet "using" the string until the loop?
I want to understand the concept for future purposes. Hope that wasn't too vague and makes some sort of sense. Thanks in advance!