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]);
}
tempis not initialized and you are using it which will lead to undefined behaviortemp. Usemalloc/callocto do it. And what did you mean by "given code should first be truncated to seven characters"?if (pa->arr[j].code == temp[i])is the same asif (pa->arr[j].code == 0). Usestrcmporstrncmpto compare two stringsstrncpy()to copy the first 7 characters ofcodetotemp, you don't need to write your own loop.