以下程序正常工作,我很惊讶为什么会这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void xyz(char **value)
{
// *value = strdup("abc");
*value = "abc"; // <-- ??????????
}
int main(void)
{
char *s1;
xyz(&s1);
printf("s1 : %s \n", s1);
}
输出:
s1 : abc
据我所知,在C语言中,如果我没有为字符串分配内存,我必须使用strdup()
函数来分配内存。但在这种情况下,通过使用" "直接给字符串赋值,程序似乎也能正常运行,有人可以解释一下吗?
s1[0] = 'x';
)。 - David Ranieri