【发布时间】:2016-11-30 13:57:07
【问题描述】:
我正在尝试理解指针,我有这个简单的例子
void third(char ****msg) {
***msg = malloc(5 * sizeof (char));
printf("\nthe msg in third is :%s ", ***msg);
strcpy(***msg, "third");
printf("\nthe msg in third after is: %s", ***msg);
// free(***msg);
}
void change(char***msg) {
**msg = malloc(5 * sizeof (char));
printf("\nthe msg in change is :%s ", **msg);
strcpy(**msg, "change");
printf("\nthe msg in change after is: %s", **msg);
third(&msg);
// free(**msg);
}
void test(char ** msg) {
*msg = malloc(5 * sizeof (char));
printf("\n the msg in test is: %s", *msg);
strcpy(*msg, "test");
printf("\nthe msg in test after is: %s\n", *msg);
change(&msg);
free(*msg);
}
int main(int argc, char** argv) {
char * msg;
test(&msg);
printf("\nthe msg back in main is: %s", msg);
}
我可以说它工作正常,但你能告诉我何时以及如何释放分配的内存,因为如果我从函数更改中删除 /// 第三个并运行它,我会遇到错误。有没有办法在每个函数的第一个打印语句中获取消息的内容 - 请参阅 otuput:
the msg in test is:
the msg in test after is: test
the msg in change is :0��
the msg in change after is: change
the msg in third is :P��
the msg in third after is: third
the msg back in main is:
有没有办法让味精发生变化是:测试然后 第三个味精是:改变
【问题讨论】:
-
简单例子?有四个开始?你已经超越了成为一名 t(h)ree-star 程序员。
-
哇!你是我看到的第一个 4 星 C 程序员!您知道成为 3 星 C 程序员已经不是恭维了,是吗?
-
@SouravGhosh:什么是树-star程序员?有人住在树上吗? ;-))
-
@Olaf 已编辑...但确实如此,如果我继续编写这样的代码,最安全的地方(避免维护者)将只是一个树屋。 ;-)
-
去掉change()和third(),从头开始分析。
标签: c pointers char malloc free