当前位置:
首页 >
下述程序有什么问题?
发布时间:2025/6/15
48
豆豆
生活随笔
收集整理的这篇文章主要介绍了
下述程序有什么问题?
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
下述程序有什么问题?
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
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;
}
解析:
1.getmemory 函数中对于指针的值来说是值传递,也就是说函数定义了一个临时变量p,p的值与str的值相同,都指向同一个地址,但是在p=(char*) malloc(100);
这句中,系统开辟了另一个空间,p指向了这个新的空间,也就是说,p和str病不指向同一个地址了,那么,接下来对×p的操作也就和str无关了,所以str的值始终没有变过,一直为null。
2.函数传入的是指针p的一个副本,而实参str没有真正被修改。因此输出为空,main函数正常返回。
为使题目功能可行,
法一:按引用传参
void getmemory(char* &p)
法二:使用指针的指针
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
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;
}
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
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;
}
解析:
1.getmemory 函数中对于指针的值来说是值传递,也就是说函数定义了一个临时变量p,p的值与str的值相同,都指向同一个地址,但是在p=(char*) malloc(100);
这句中,系统开辟了另一个空间,p指向了这个新的空间,也就是说,p和str病不指向同一个地址了,那么,接下来对×p的操作也就和str无关了,所以str的值始终没有变过,一直为null。
2.函数传入的是指针p的一个副本,而实参str没有真正被修改。因此输出为空,main函数正常返回。
为使题目功能可行,
法一:按引用传参
void getmemory(char* &p)
法二:使用指针的指针
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
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;
}
总结
以上是生活随笔为你收集整理的下述程序有什么问题?的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 如果有一个类是 myClass , 关于
- 下一篇: Which of the followi