问题描述
我不清楚字符指针及其工作原理.
I am not so clear on character pointer and how they work.
该程序已构建,但在运行时崩溃.
The program builds, but crashes when I run it.
char *ab = NULL;
//ab = "abc123"; // works fine
sprintf(ab, "abc%d", 123); // this line seems to crash the program
当sprintf将(char * str)作为第一个参数时,我不知道这怎么错.
I don't get how this can be wrong, when sprintf takes in a (char * str) as a first argument.
任何人都可以向我解释一下吗?
Can anyone please explain this to me?
推荐答案
您尚未分配要与ab
一起使用的内存.
You have allocated no memory to use with ab
.
第一个分配起作用是因为您要向ab
分配一个字符串常量:"abc123"
.常量字符串的内存由编译器代表您提供:您不需要分配此内存.
The first assignment works because you are assigning to ab
a string constant: "abc123"
. Memory for constant strings are provided by the compiler on your behalf: you don't need to allocate this memory.
例如,在将ab
与sprintf
,您需要使用malloc
分配一些内存,并将该空间分配给ab
:
Before you can use ab
with e.g. sprintf
, you'll need to allocate some memory using malloc
, and assign that space to ab
:
ab = malloc(sizeof(char) * (NUM_CHARS + 1));
然后,只要您使用malloc
留出了足够的空间,您的sprintf
就可以工作.注意:+ 1
用于为空终止符.
Then your sprintf
will work so long as you've made enough space using malloc
. Note: the + 1
is for the null terminator.
或者,您可以通过将其声明为数组来为ab
腾出一些内存:
Alternately you can make some memory for ab
by declaring it as an array:
char ab[NUM_CHARS + 1];
在不为ab
分配内存的情况下,sprintf
调用将尝试写入NULL
,这是未定义的行为.这是导致崩溃的原因.
Without allocating memory somehow for ab
, the sprintf
call will try to write to NULL
, which is undefined behavior; this is the cause of your crash.
这篇关于C语言中的char指针初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!