[英]How to find an element in an array of structs in C?
我必須編寫一個函數來查找具有給定數組的給定代碼的產品。 如果找到product,則返回指向相應數組元素的指針。
我的主要問題是給定的代碼應首先截斷為7個字符,然后才與數組元素進行比較。
非常感謝你的幫助。
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]);
}
你為什么不在循環中使用strncmp?
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;
}
temp
是一個未初始化的指針,你正在取消引用它,這將導致未定義的行為。
temp = malloc(size); // Allocate some memory size = 8 in your case
我看到的另一個錯誤是
if (pa->arr[j].code == temp[i]) // i is already indexing `\0`
應該
strcmp(pa->arr[j].code,temp); // returns 0 if both the strings are same
如果你可以使用strncmp()完全可以避免這個代碼
正如其他人所指出的,你正在使用temp
未初始化,並且你總是將字符與'\\0'
進行比較。
您不需要temp
變量:
int strncmp(const char * str1,const char * str2,size_t num);
比較兩個字符串的字符
將C字符串str1的最多num個字符與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 */
}
當你寫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個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.