我想了解指針和我有這個簡單的例子c char字符數組,指針,malloc的,免費
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);
}
我可以說,這是工作正常,但你能告訴我什麼時候以及如何我需要釋放分配的內存,因爲如果我從函數中刪除//更改,並運行它,我有錯誤。 ,是有辦法讓每個函數的第一個print語句的消息的內容 - 看到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:
有沒有辦法讓在變化中味精是:測試,然後 味精第三個是:更改
你「擁有」什麼「錯誤」? –
簡單的例子?有四個開始?你已經遠遠超過了成爲一名高級程序員。 –
哇!你是我看到的第一個C程序員!你知道作爲一個三星級的C程序員已經不是恭維了,對嗎? – Olaf