何时使用字符指针的malloc [英] When to use malloc for char pointers
问题描述
我特别注重时使用的字符指针的malloc
I'm specifically focused on when to use malloc on char pointers
char *ptr;
ptr = "something";
...code...
...code...
ptr = "something else";
请问一个malloc是为了微不足道,因为这东西吗?如果是,为什么?如果没有,那么当它是必要的字符指针?
Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?
推荐答案
正如其他人所指出的,你不只是需要使用malloc做的事:
As was indicated by others, you don't need to use malloc just to do:
const char *foo = "bar";
这其中的原因正是 *富
的是的指针—在初始化富
你没有创建字符串的副本,只是一个指针,其中栏
生活在你的可执行文件的数据部分。您可以复制指针经常你愿意,但要记住,他们总是回指向该字符串的同一个实例。
The reason for that is exactly that *foo
is a pointer — when you initialize foo
you're not creating a copy of the string, just a pointer to where "bar"
lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.
所以,当你要使用malloc?通常你用的strdup()
复制一个字符串,它在后台处理malloc的。例如。
So when should you use malloc? Normally you use strdup()
to copy a string, which handles the malloc in the background. e.g.
const char *foo = "bar";
char *bar = strdup(foo); /* now contains a new copy of "bar" */
printf("%s\n", bar); /* prints "bar" */
free(bar); /* frees memory created by strdup */
现在,我们终于得到周围,你可能想如果你使用的sprintf()
,或更安全的的snprintf到malloc的情况下, ()
它创建/格式化一个新的字符串。
Now, we finally get around to a case where you may want to malloc if you're using sprintf()
or, more safely snprintf()
which creates / formats a new string.
char *foo = malloc(sizeof(char) * 1024); /* buffer for 1024 chars */
snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */
printf(foo); /* prints "foo - bar" */
free(foo); /* frees mem from malloc */
这篇关于何时使用字符指针的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!