Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element in an array of structs in C?

Tags:

arrays

c

struct

I have to write a function that finds a product with given code from the given array. If product is found, a pointer to the corresponding array element is returned.

My main problem is that the given code should first be truncated to seven characters and only after that compared with array elements.

Would greatly appreciate your help.

struct product *find_product(struct product_array *pa, const char *code) 

{   
char *temp;
int i = 0;
    while (*code) {
        temp[i] = (*code);
        code++;
        i++;
        if (i == 7)
            break;
    }
    temp[i] = '\0';

for (int j = 0; j < pa->count; j++)
    if (pa->arr[j].code == temp[i])
        return &(pa->arr[j]);
}
like image 385
caddy-caddy Avatar asked Apr 09 '15 07:04

caddy-caddy


People also ask

How do you access an element in an array of structs?

Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures.

How do I find an element in an array of arrays?

Use forEach() to find an element in an array The Array. prototype. forEach() method executes the same code for each element of an array. The code is simply a search of the index Rudolf (🦌) is in using indexOf.

Can you have an array of structs in C?

An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types.


1 Answers

Why don't you just use strncmp in a loop?

struct product *find_product(struct product_array *pa, const char *code) 
{ 
   for (size_t i = 0; i < pa->count; ++i)
   {
      if (strncmp(pa->arr[i].code, code, 7) == 0)
          return &pa->arr[i];
   }
   return 0;
}
like image 162
michaelb Avatar answered Sep 28 '22 14:09

michaelb