Comparison with string literal results in unspecified behaviour?

前端 未结 4 1257
独厮守ぢ
独厮守ぢ 2020-12-17 17:45

I am having a problem with the program I am trying to code. It\'s just a Windows console program and I am very new to C++. It\'s only my 4th program.

The problem I a

相关标签:
4条回答
  • 2020-12-17 17:50

    You're comparing pointers, not the actual strings. Use C++ string class instead of char* (or check how C strings work).

    0 讨论(0)
  • 2020-12-17 17:56

    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 above's error message.

    0 讨论(0)
  • 2020-12-17 18:10

    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.

    0 讨论(0)
  • 2020-12-17 18:14

    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 can't 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!

    0 讨论(0)
提交回复
热议问题