Question

I'm studying C language on my own. Can someone give me a hint on problem below? (Just a hint is good and I'll work on it from there.) Thanks.

The symptom is that the index number printed is always 0.

print("\n\n  Lookdown: start with a value and get the index of the match  \n");
  char myArrayOfLetters2[] = {'w','x','y','z'};
  char myLookUpValue = "y";
  int myResultIndexNumber;
  int myArrayCounter;

  for (myArrayCounter=0; myArrayCounter<sizeof(myArrayOfLetters2); myArrayCounter++){
    if (myArrayOfLetters2[myArrayCounter] == myLookUpValue){
            myResultIndexNumber=myArrayCounter;} //found
  } // loop thorugh all members of array
print("myLookUpValue of 'y' returned index number of %d",myResultIndexNumber);
Was it helpful?

Solution

char myLookUpValue = "y";

"y" is not a char, it's a string (const char[]). Arrays decay to pointers to their first element when appropriate. You're converting the address of that array (a pointer to its first element) to a char (turn on your warnings). You wanted:

char myLookUpValue = 'y';

OTHER TIPS

Use single quotes:

char myLookUpvalue = 'y';

this is really simple I think, all I shall say is that you are assigning a string "y" to a char. Line 3 should be char myLookUpValue = 'y';

Your code will assign a lowest 8 bits of a pointer to constant string containing 'y' which is a memory location and will be very unlikely to equal the char code of 'y'.

One major problem is here:

char myLookUpValue = "y";

The expression "y" is a string literal and has type "2-element array of char" with the contents {'y', 0}. To define a character literal, use single quotes instead:

char myLookupValue = 'y';

Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

In your code, the expression"y" is not the operand of the sizeof or unary & operators, and while it's being used to initialize something in a declaration, that something isn't an array of char, so it's converted to a pointer type and its value is the address of first letter of the string in storage. That address value is then converted to type char and assigned to myLookupValue; the result is most likely not any of 'w', 'x', 'y', or 'z'. so the comparison fails.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top