0

I have the following case:

An array is defined as an unsigned integer:

uint8 myArray[6][10] = {"continent","country","city","address", "street", "number"};

Now I want to get for example the index of the string "city". I imagine to do something like this:

uint8 idx;

for(idx = 0; idx < sizeof(myArray)/sizeof(myArray[0];i++))
{
    if((myArray[idx]) == "city")   // This can not work because the array is an uint8 array
    {
         /*idx = 2 ....*/
    }
}

What is the correct way to do it without using functions from string.h like strcpy etc...

JohnDoe
  • 825
  • 1
  • 13
  • 31
  • Does this answer your question? [How do I properly compare strings?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings) – Mathieu Mar 06 '20 at 09:21
  • You may have a look here https://stackoverflow.com/q/55967430 – Marco Frau Mar 06 '20 at 09:26

2 Answers2

1

As pointed out by others you can not compare two C strings with the equal operator =, instead you need to use strcmp, and since you are not allowed to use it you need to implement it yourself.

Here the implementation of strcmp in glibc

So your code can be something like:

int mystrcmp(const uint8 *s1, const uint8 *s2)
{
    uint8 c1, c2;
    do
    {
        c1 = *s1++;
        c2 = *s2++;
        if (c1 == '\0')
            return c1 - c2;
    }
    while (c1 == c2);
    return c1 - c2;
}
....
uint8 *str = "city";
size_t size = sizeof(myArray) / sizeof(myArray[0]);
size_t idx;

for (idx = 0; idx < size; i++)
{
    if (mystrcmp(myArray[idx], str) == 0)
    {
        break;
    }
}
if (idx == size)
{
    printf("'%s' was not found\n", str);
}
else
{
    printf("'%s' was found at index %zu\n", str, idx);
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

You need to compare the strings character-by-character.

For this you write a loop going from the first character until it finds an unmatched character or an end-of-string marker in either string, what ever comes first.

Since it sounds like homework, I will not post code.

the busybee
  • 10,755
  • 3
  • 13
  • 30
  • I found the solution. Thanks! It's not any home work or similar. Just training by my own to improve some c skills. – JohnDoe Mar 06 '20 at 12:25