千家信息网

字符指针与字符串

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,void getmemory(char p){p=(char ) malloc(100);strcpy(p,"hello world");}int main( ){char *str=NULL;get
千家信息网最后更新 2025年12月02日字符指针与字符串

void getmemory(char p)
{
p=(char
) malloc(100);
strcpy(p,"hello world");
}
int main( )
{
char *str=NULL;
getmemory(str);
printf("%s/n",str);
free(str);
return 0;
}会出现什么问题?
【标准答案】程序崩溃,getmemory中的malloc 不能返回动态内存, free()对str操作很危险。

参考网上的代码:
void getmemory(char *p)
{
p=(char ) malloc(100);
strcpy(
p,"hello world");
}
int main( )
{
char str=NULL;
getmemory(&str);
printf("%s/n",str);
free(str);
return 0;
}
个人注解:
char
str=NULL;相当于定义一个字符串str,也是字符指针str。
getmemory(&str);传的是字符串地址。
char *p可看成是 (char )p意为字符串str的指针p。
p为字符串str。亦是单字符的指针str。

0