0

This is my current code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int target;
    char array[] = {'AC', 'EE', '88', '0D', '87'};

    printf("Enter the target byte as a hex value: \n");
    scanf("%x", &target);

    int i = 0;
    for (i; i < 5; i++)
    {
        printf("Value of array[%d] is %x \n", i, array[i]);
    }

    int i = 0;
    for (i; i < 5; i++)
    {
        if (memcmp(target, array, sizeof(target) == 0))
        {
            printf("Found a match!");
        }
    }
}

(1) I want to be able to display to stdout the exact values inside of my char array[]. Things I've tried that do not work: displaying the array as %c, %x, %d.
(2) After I get the input from the user, I want to be able to compare that input to the characters inside of the array - figured memcmp would be the way to go, but how do I traverse through the entire array? I tried doing if (memcmp(target, array[i], sizeof(target) == 0)) but I'd get a runtime error because of the array[i] part, but if I don't add that part, how will it go through the entire array comparing the values stored in each array memory location to the value stored in the target variable? I basically want to compare bytes inside each array location to the bytes the input by the user.

relapsn
  • 85
  • 7
  • 3
    Try with `char array[] = {0xAC, 0xEE, 0x88, 0x0D, 0x87};`. And print using `%x`. Other thing your `memcmp` call is wrong. You can just compare `if (target == array[i])`. – Murilo Vasconcelos Oct 09 '13 at 21:46
  • 1
    Have you tried to compile it - it does not - see http://cfiddle.net/aLgUal. Here is a good starting point. Get it to compile! – Ed Heal Oct 09 '13 at 21:52
  • ..just remove the second `int i = 0` and it compiles just fine, thanks. Anyway, @MuriloVasconcelos, I tried initializing my array to what you said, and now my problem is that those initialized values are being displayed as `ffffffac, ffffffee, ffffff88` etc, so how do I make my comparison ignore the leading `ffffff`? – relapsn Oct 09 '13 at 21:58
  • It is because it is a signed array. Try this way: `unsigned char array[] = {0xAC, 0xEE, 0x88, 0x0D, 0x87};`. – Murilo Vasconcelos Oct 09 '13 at 22:00
  • I was just about to type that I changed it since I just noticed that, ha. Thank you, though! However, your suggestion of `if (target == array[i])` does not work for some reason, and I tried that earlier too and couldn't get it to work thus why I considered using `memcmp()`. Any suggestions on the comparing part? – relapsn Oct 09 '13 at 22:03
  • Nevermind, I found the solution. I uploaded it here:http://codepad.org/pDtqRBSd. Thank you for your help! – relapsn Oct 09 '13 at 22:05
  • @relapsn You can add your solution as an answer to your own question. Although I'd use sizeof(array) to get the length instead of getting an end point with an explicit +5. – Iskar Jarak Oct 09 '13 at 22:18
  • I'll do that now, thanks. – relapsn Oct 09 '13 at 22:47

2 Answers2

1
  1. You should store the hex values in your array as 0xAC etc, not 'AC' (which is a multi character constant and not at all what you want).
  2. Store your hex values as unsigned char because on platforms where char defaults to signed you're going to get some values (negative ones) being cast to int and sign-bit padded accordingly, which is then displayed.
  3. Your memcmp is call wrong and using it is unnecessary anyway.
  4. Your example code won't compile because you have two declarations of int i in the same scope. If you aren't using C89 why aren't you writing your for loops as for(int i = 0;...) anyway?
  5. Don't forget your return value for main.

Example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int target;
  const unsigned char array[] = { 0xAC, 0xEE, 0x88, 0x0D, 0x87 };
  const int len = sizeof array;

  printf("Enter the target byte as a hex value: \n");
  scanf("%x", &target);

  for (int i = 0; i < 5; ++i)
  {
    printf("Value of array[%d] is 0x%x\n", i, array[i]);
  }

  for (int i = 0; i < len; ++i)
  {
    if (target == array[i])
    {
      printf("Found a match!\n");
    }
  }

  return EXIT_SUCCESS;
}
Iskar Jarak
  • 5,136
  • 4
  • 38
  • 60
  • Thank you! I already got my answer before you answered this, but your response brought up something I've been meaning to ask. I'm using Code::Blocks to program in C/C++, and when using C I can't use `for (int i = 0; //etc` because the compiler tells me it's using C89. How do I update my compiler to a more recent one? – relapsn Oct 09 '13 at 22:38
  • Haha, was just about to say that. What compiler are you using btw? You might want to look into warning and error flags like `-Wall` (for gcc and clang). In fact I strongly recommend you do. – Iskar Jarak Oct 09 '13 at 22:47
  • I'm using the GNU GCC compiler. And those were enabled by default, thanks! – relapsn Oct 09 '13 at 22:51
1

This question was part of a bigger program, but it was just this small portion that I couldn't figure out to begin with. In the end, I got everything worked out. Below is the final code of the actual program, and at the bottom are the function definitions I wrote with the help of a couple of users. Again, thank you!

#include    <stdio.h>
#include    <stdint.h>
#include    <stdlib.h>


// defined constants
#define MAX_WIDTH       20
#define NUMELEMS        50


// typedefs and function prototypes
typedef unsigned char   Byte;
void DispBytes(void *voidArray, int totalBytes);
int CountMatchBytes(void *voidArray, int totalBytes, int targetHex);


// ==== main ==================================================================
//
// ============================================================================

int     main(void)
{
    auto    double          myDoubles[NUMELEMS];
    auto    int             myInts[NUMELEMS];
    auto    char            myChars[NUMELEMS];
    auto    int             target;
    auto    int             numMatches;

    // process the char array
    puts("Here's the array of chars as bytes: ");
    DispBytes(myChars, sizeof(myChars));
    printf("\nEnter the target byte as a hex value: ");
    scanf("%x", &target);
    numMatches = CountMatchBytes(myChars, sizeof(myChars), target);
    printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
                                             , numMatches
                                             , (1 == numMatches ? "" : "s"));
    // process the int array
    puts("\nHere's the array of ints as bytes: ");
    DispBytes(myInts, sizeof(myInts));
    printf("Enter the target byte as a hex value: ");
    scanf("%x", &target);
    numMatches = CountMatchBytes(myInts, sizeof(myInts), target);
    printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
                                             , numMatches
                                             , (1 == numMatches ? "" : "s"));
    // process the double array
    puts("\nHere's the array of doubles as bytes: ");
    DispBytes(myDoubles, sizeof(myDoubles));
    printf("Enter the target byte as a hex value: ");
    scanf("%x", &target);
    numMatches = CountMatchBytes(myDoubles, sizeof(myDoubles), target);
    printf("There %s %d matching byte%s.\n\n", (1 == numMatches ? "is" : "are")
                                             , numMatches
                                             , (1 == numMatches ? "" : "s"));

    return  0;

}  // end of "main"

void DispBytes(void *voidArray, int totalBytes)
{
    // Sets startingPtr to the base address of the passed array
    auto unsigned char *startingPtr = voidArray;
    // Sets endingPtr to one address past the array
    auto unsigned char *endPtr = voidArray + totalBytes;
    auto int counter = 0;

    // Loop while the address of startingPtr is less than endPtr
    while (startingPtr < endPtr)
    {
        // Display the values inside the array
        printf("%x ", *startingPtr);
        counter++;

        if (counter == MAX_WIDTH)
        {
            printf("\n");
            counter = 0;
        }
        // Increment the address of startingPtr so it cycles through
        // every value inside the array
        startingPtr++;
    }
}

int CountMatchBytes(void *voidArray, int totalBytes, int targetHex)
{
    // Sets startingPtr to the base address of the passed array
    auto unsigned char *startingPtr = voidArray;
    // Sets endingPtr to one address past the array
    auto unsigned char *endingPtr = voidArray + totalBytes;
    auto int counter = 0;
    // Loop while the address of startingPtr is less than endPtr
    while (startingPtr < endingPtr)
    {
        // If the input value is the same as the value inside
        // of that particular address inside the array,
        // increment counter
        if (targetHex == *startingPtr)
        {
            counter++;
        }
        // Increment the address of startingPtr so it cycles through
        // every value inside the array
        startingPtr++;
    }
    // Return the number of times the input value was found
    // within the array
    return counter;
}
relapsn
  • 85
  • 7