I am writing a member function for a class where I would like to print out some dynamically allocated array according to the string name passed to the member function. The following code somehow get a compilation error:
error: 'tmp' was not declared in this scope
How should I do the coding? What is the problem of my code?
void backgrnd::print(const char m[]){
if (m == "interior")
int* tmp = this->interior;
else if (m == "fB")
float* tmp = this->fB;
for (int i=0;i<this->n_vox;++i)
cout << tmp[i] << ' ';
}
There are a few problems with your code.
You’re passing a string by pointer (writing
const char []is quite the same as writingconst char *– BTW,constis left associative and you could write it aschar const *as well).Anyway, in the next line you’re comparing this pointer
mwith the pointer refering to the string literal constant"interior"And this does not what you had most likely in mind. This operation compares the values of the pointers and not the strings! The pointers would only compare as equal, if the pointer you passed to the function was that of the same string literal
"interior", which is very unlikely the case. If it was just any other string, even if it also contained the character sequenceinterior, it would not compare equal. It would also happen if the compiler and/or linker didn’t redact redundant string literals into a single pointer constant.And of course the other pointer – string literal comparisions suffer from the same problem.
Now the next problem is, that you create a scoped pointer variable
tmp, which you initialize with some instance class member pointer variable of the same type. But as soon as the scope is left that variable is no longer visible…… and this for loop can no longer see it. Now this loop is problematic by itself, because it’s unclear what
n_voxmeans.I guess you wrote the above to save some code duplication below. The problem is: C++ is a statically typed language so the following statement can not “dynamically” type to the type of the
tmpvariable.Here are a few suggestions:
when using C++ you should use std::string instead of naked char arrays. This also makes the equality operator
==do what you naively expected. If you insist on using C-style char arrays, use a string comparision function likestrncmp.Since you need to write statically typed
cout<<statements anyway, move that loop into theifclauses. Use curly braces to enclose them!.