【发布时间】:2020-09-07 16:31:34
【问题描述】:
对于一个作业,我被要求更改包含“Hello World!”的字符串str3。到“你好”,并使用realloc() 删除exess 内存。我真的不知道该怎么做。
- 如何使用
realloc()截断字符串? - 如何更改“Hello World!”中的字符串“你好”?
DString 是一个 char* 指针,所以 DString *str 是一个双指针 char**。
我们从main()函数发送str3,其中包含“Hello World!”以及函数shrinkDString() 的空白空间。
int main() {
shrinkDString(&str3, ' '); // truncate str3 after the blank, only "Hello" remains
shrinkDString(&str3, ' '); // nothing happens, "Hello" remains the same
}
作为前置条件和后置条件,我应该使用assert()。 DString *str 是指向 str3 的双指针,ch 是空白空格。存储“你好世界!”在str3 使用包括\0 在内的13 个内存,“Hello”应该只使用包括\0 在内的6 个内存。
void shrinkDString(DString *str, char ch) {
// Shrinks the DString *str up to the first occurence of ch.
// Precondition: str is not NULL
// Precondition: *str is not NULL
/* Postcondition: if str has been truncated, its new length corresponds to the position of ch in the
original str*/
/* Tips:
- think that str is already allocated in memory and may be changed! Only the proper amount of
memory for storing the truncated string is allocated when the function return
- do not forget the char for ending a string '\0'
- useful C functions: realloc.
*/
}
这是我迄今为止尝试过的,但是当使用 realloc() 和 assert(*str != NULL); 取消引用 NULL 指针时出现内存泄漏。
void shrinkDString(DString *str, char ch) {
assert(str != NULL);
assert(*str != NULL);
*str = (char*)realloc(*str, 6);
}
我不知道如何继续。感谢您的帮助!
【问题讨论】:
-
Axel Foolya,很好奇,为什么在
*str = (char*)realloc(*str, 6);中使用演员(char*)而不是仅使用*str = realloc(*str, 6);?