您的位置:首页 > 其它

指针赋值

2014-10-31 10:00 162 查看
int main()
{
char *ptr=NULL;
get_str(ptr);
if(ptr)
printf("%s",ptr);
else
printf("%p\n",ptr);
return 0;
}
void get_str(char *p)
{
p=(char*)malloc(1+sizeof("testing"));
strcpy(p,"testing");
}

函数的问题在于,函数接收的参数p,并不是最终能够获得字符串的p。

传递的指针类型的参数,是用来改变其指向内容的,而指针本身的值不会改变。

所以在这个函数中,给p分配的内存,使p指向这段内存的首地址,但调用者传入的p这个参数本身并没有改变,如果原来是NULL,那么函数调用返回后,这个p还是NULL,会出现访问异常.

第一种办法: 要先给p分配好内存,再调用函数。在函数中不能进行内存分配操作。

#include <stdio.h>
#include <string.h>
void get_str(char *p)
{
strcpy(p,"testing");
}
void   main()
{
char *p;
p = (char *)malloc(256);
get_str(p);
printf("the string:  %s \n",p);
}


第二种办法: 还有就是函数将分配的地址返回出来,在函数中分配内存,供调用者使用。

#include <stdio.h>
#include <string.h>
char*  get_str()
{
char * p;
p = (char *)malloc(sizeof("testing"));
strcpy(p,"testing");
return p;
}
void   main()
{
char *p;
p = get_str();
printf("the string:  %s \n",p);
}


第三种办法: 就是将函数指针的指针传入函数,在函数中分配内存。

#include <stdio.h>
#include <string.h>
void  get_str(char **p)
{
*p = (char *)malloc(sizeof("testing"));
strcpy(*p,"testing");
}
void   main()
{
char *p;
get_str(&p);
printf("the string:  %s \n",p);
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: