如何解决C:查找并删除结构体成员
我以这种方式声明了两个结构:
struct record {
const char *entry;
struct record *next;
};
struct s_table {
int capacity;
struct record *records;
};
然后我写了一个删除s_table结构成员的方法:
int s_table_remove_record(struct s_table *t,const char *begin,const char *end) {
if (!t) {
printf("No table");
return 0;
}
printf("inside remove_record \n");
if (strcmp(begin,t->records->entry) == 0) {
printf("record found in the first if.");
struct record *temp = t->records->next;
free(t);
return 1;
}
printf("Before allocating the head\n");
struct record *head = t->records;
for (; t->records->next; t->records = t->records->next) {
printf("Inside the for loop \n");
if (strcmp(begin,t->records->entry) == 0) {
printf("record found in the second if");
struct record *temp = t->records->next;
t->records->next = t->records->next->next;
free(temp);
return 1;
}
}
printf("record not found\n");
return 0;
}
但是我从来没有进入for循环。您能帮我理解原因并提供解决方案吗?
要测试代码:
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct record {
const char *entry;
struct record *next;
};
struct s_table {
int capacity;
struct record *records;
};
static int counter = 0;
struct s_table *s_table_new() {
struct s_table *t = (struct s_table *)malloc(sizeof(t));
t->capacity = 1000;
t->records = (struct record *)malloc(sizeof(struct record) * t->capacity);
return t;
}
int s_table_add_record(struct s_table *t,const char *end) {
if (!t) {
printf("No table");
return 0;
}
if (counter > t->capacity) {
printf("Not enough space!");
return 0;
}
t->records[counter].entry = begin;
printf("Record add is: %s \n",t->records[counter].entry);
if (!t) {
printf("Failed to allocate new recrd");
return 0;
}
return 1;
}
int main() {
static const char *tomatoes = "tomatoes 10Kg CHF 55";
static const char *carrots = "carrots 15Kg CHF 40";
static const char *peppers = "peppers 2Kg CHF 6";
struct s_table *t = s_table_new();
assert(t);
s_table_delete(t);
struct s_table *t2 = s_table_new();
assert(t2);
t = s_table_new();
assert(t);
s_table_delete(t2);
s_table_add_record(t,carrots,carrots + strlen(carrots));
printf("First record added\n");
s_table_add_record(t,carrots + strlen(carrots));
printf("Second record added \n");
s_table_add_record(t,carrots + strlen(carrots));
s_table_add_record(t,peppers,peppers + strlen(peppers));
s_table_add_record(t,tomatoes,tomatoes + strlen(tomatoes));
printf("All records added \n");
s_table_remove_record(t,peppers + strlen(peppers));
return 1;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。