Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

Why doesnt this simple "if" work? problem with char variable

I am learning C, and generally have a pretty good grasp on the basics.  However, the char variables are messing me up.  I dont have a firm grasp on how to use char[] arrays vs char *...

Why wont these if's validate?  The urgency is because I have an assignment due that is failing because of a problem like below
  float RateA, RateB, amount;
  char *MoneyTo_str, *MoneyFrom_str;

int main() {
  MoneyFrom_str = "DOLLARS";
  MoneyTo_str = "EUROS";

  if ( MoneyFrom_str == "DOLLARS") {
    RateA = 2.00; }
      printf(" error MoneyFrom_str\n");
  if ( MoneyTo_str == "EUROS") {
    RateB = 4.00; }
      printf(" error MoneyFrom_str\n");
2 Solutions
You should use strcmp to compare strings.. Check out the following FAQ page for details:


Jaime OlivaresSoftware ArchitectCommented:
>I dont have a firm grasp on how to use char[] arrays vs char *...

Some hints:
You must use char[] to create "buffers" where you want to store some strings (usually with strcpy).
But, if strings previously exist (in another buffer) or is a literal like "DOLLARS", then you don't have to declare an array, just have to point it, a pointer, countersense buffers, don't have a space where to put the string.

This kind of comparison is not valid in C:

if ( MoneyTo_str == "EUROS") {

because MoneyTo_str is a pointer to a string (maybe filled, maybe not), but represents a memory position like 0x12AC568F.
The literal "EUROS" also represents a memory position, if both are pointing to the same memory position, the comparison will be true, but if both point to different memory positions, EVEN if both memory position contains the SAME string, comparison will be false.
vettoAuthor Commented:
Points to both, Gripe answered the question the way I love..by giving me the "book" and saying "read this"

jaime explained WHY this wont work (thus points)...I am pretty good at a few interpreted languages where a string value is exactly that, and a var is that value -  not a pointer to an area in memory, so you can see my confusion.  Thanks for the explaination.

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now