所以我被设置了一个任务,即创建一个人造字符串结构并在我的人造字符串结构上实现所有常用的字符串函数。我被困在名为append 的strcat 实现的测试中,第一个测试失败(段错误)是第5 行。我用于创建新结构的函数应该没问题,因为它通过了所有测试,但我将其包含在内只是为了以防万一。
我已经能够成功地为我的人造字符串结构实现长度、获取、设置和复制函数。
结构:
struct text {
int capacity;
char *content;
};
typedef struct text text;
我创建新结构的函数:
text *newText(char *s) {
printf("new Text from %s\n", s);
int sizeNeeded = (strlen(s)+1);
int sizeGot = 24;
while (sizeNeeded > sizeGot) {
sizeGot = sizeGot * 2;
}
text *out = malloc(sizeGot);
char *c = malloc(sizeGot);
strcpy(c, s);
out->content = c;
out->capacity = (sizeGot);
printf("the capacity is %d\n", sizeGot);
return out;
free(c);
}
我的附加功能:
void append(text *t1, text *t2) {
printf("t1 content is %s, t2 content is %d\n", t1->content, *t2->content);
int sizeNeeded = (t1->capacity + t2->capacity);
int sizeGot = 24;
while (sizeNeeded > sizeGot) {
sizeGot = sizeGot * 2;
}
char *stringy = calloc(sizeGot, 32);
stringy = strcat(t1->content, t2->content);
free(t1);
t1 = newText(stringy);
}
最后是测试:
void testAppend() {
text *t = newText("car");
text *t2 = newText("pet");
append(t, t2);
assert(like(t, "carpet"));
assert(t->capacity == 24);
text *t3 = newText("789012345678901234");
append(t, t3);
assert(like(t, "carpet789012345678901234"));
assert(t->capacity == 48);
freeText(t);
freeText(t2);
freeText(t3);
}
最佳答案
您分配内存的方式错误。您可以通过使用灵活的数组成员来解决这个问题,如下所示:
typedef struct {
int capacity;
char content[];
} text;
text *out = malloc(sizeof(text) + sizeof(something));
strcpy(out->content, str);
...
显然这样的代码是无意义的:
return out;
free(c);
}
启用编译器警告并听取它们。
关于c - 在 C 中使用 void 函数操作结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371504/