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

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

My main problem is that this code must first be truncated to seven characters and only after that compared to the elements of the array.

Many thanks for 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]);
}
+4
source share
4 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;
}
+10
source

temp is a pointer that is not initialized, and you are looking for it, which will lead to undefined behavior.

temp = malloc(size); // Allocate some memory size = 8 in your case

Another mistake I see is

if (pa->arr[j].code == temp[i]) // i is already indexing `\0` 

it should be

strcmp(pa->arr[j].code,temp); // returns 0 if both the strings are same

, strncmp()

+4

, temp uninitialized, '\0'.

temp:

int strncmp (const char * str1, const char * str2, size_t num);

C string str1 C str2.

/* Don't use magic numbers like 7 in the body of function */
#define PRODUCT_CODE_LEN 7

struct product *find_product(struct product_array *pa, const char *code) 
{   
    for (int i = 0; i < pa->count; i++) {
        if (strncmp(pa->arr[i].code, code, PRODUCT_CODE_LEN) == 0)
            return &(pa->arr[i]);
    }
    return NULL; /* Not found */
}
+2

char* temp;,

, , 7,

char temp[8];

temp[i] = (*code);
code++;
i++;

:

temp[i++] = *code++;

for (int j = 0; j < pa->count; j++)
    if (pa->arr[j].code == temp[i])
        return &(pa->arr[j]);

code temp[i], , , 8 .

, , , temp:

for (int j = 0; j < pa->count; j++)
    if (!strncmp(pa->arr[j].code, temp, 7)
        return &(pa->arr[j]);

return NULL;, , , .

, , temp [] 7 .

+1
source

All Articles