指针赋值
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); }
相关文章推荐
- Linux内核中常见的结构体对象中的函数指针赋值操作
- 复习指针数组以及如何把二维数组赋值给二维指针
- C/C++中,为什么字符串可以赋值给字符指针变量,单引号和双引号的区别
- C语言指针的初始化和赋值
- 指针赋值,加减,比较
- c语言实现函数给主函数中的指针赋值的方法
- 指针将数值赋值到制定内存地址
- C-指针赋值总结
- 指针,野指针,空指针,赋值?
- 指针的赋值运算
- 指针间接赋值
- C语言指针的初始化和赋值
- C语言指针的初始化和赋值
- 基类指针和子类指针相互赋值
- C++多态总结:多态原理、虚函数指针、重载重写 ,赋值兼容性原则
- 指针的赋值和内存访问
- 不要再直接用字符串常量给字符串指针初始化/赋值了
- C语言指针的初始化和赋值
- 【C语言提高08】【指针铁律】铁律2:间接赋值(*p)是指针存在的最大意义