指针赋值

来源:互联网 发布:怎么修改手机的mac地址 编辑:程序博客网 时间:2024/06/05 23:08
int main(){char *ptr=NULL;get_str(ptr);if(ptr)printf("%s",ptr);elseprintf("%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);}


0 0
原创粉丝点击