c++ – Comparison with string literal results in unspecified behaviour?
c++ – Comparison with string literal results in unspecified behaviour?
In C++ ==
only implemented internally for primitive types and array is not a primitive type, so comparing char[100]
and string literal will only compare them as 2 char*
or better to say as 2 pointers and since this 2 pointers cant be equal then items[n] == ae
can never be true, instead of this you should either use std::string
to hold string as:
std::string items[100];
// initialize items
if( items[n] == ae ) ...
or you should use strcmp
to compare strings, but remeber strcmp
return 0 for equal strings, so your code will be as:
char items[100][100];
// initialize items
if( strcmp(items[n], ae) == 0 ) ...
And one extra note is if (items == 0)
is useless, since items
allocated on stack and not in the heap!
First, int * price;
is a dangling pointer – you never initialize it. You have to do:
int * price = new int[i];
Second, usually, i
denotes an iterator index so I suggest you stick with that – so
for (i=0; i<n; i++) //some more refactoring needed
Third, you need to compare char arrays using strncmp
in your case.
Fourth and most important – use std::string
and std::vector
instead. This is C++, not C.
c++ – Comparison with string literal results in unspecified behaviour?
Just a little thing that got me stumbling for a bit, is the difference between single and double quotes, see: Single quotes vs. double quotes in C or C++
I was comparing the first character of a string with double quotes and not single quotes – which resulted in aboves error message.
Related posts on c++ :
- c++ – InterlockedIncrement usage
- c++ – How do I render a triangle in QOpenGLWidget?
- visual c++ – filling up an array in c++
- loops – C++ – using glfwGetTime() for a fixed time step
- c++ – Eigen – get a matrix from a map?
- python 2.7 – Microsoft Visual C++ 9.0 is required
- c++ error: invalid types int[int] for array subscript
- c++ – no default constructor exists for class