#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void allocateSpace(char *pp)
{
char *temp = malloc(100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
pp = temp;
}
void test02()
{
char *p = NULL;
allocateSpace(p);
printf("p=%s\n", p);
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}
memset的用法
#include <stdio.h>
#include <string.h>
int main ()
{
char str[50];
strcpy(str,"This is string.h library function");
puts(str);
memset(str,'$',7);
puts(str);
return(0);
}
//打印后的结果如下所示:
//This is string.h library function
//$$$$$$$ string.h library function
**开始的时候,char *p和char pp在内存中开辟数据,然后在堆区申请一篇内存全直0,接着定义一个指针char temp来指向堆区的首地址。在文字常量区的值传入到堆区。
整个流程为以下三步,所以打印出来为NULL
在test02()中我们一般叫它为主调函数,主调函数中这个指针为空,那么被调函数用同级的指针来修饰它,是修饰不成功的。那么想要改就要用二级指针。
接下来就是修改后的案例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void allocateSpace(char *pp)
{
char *temp = malloc(100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
pp = temp;
}
void test02()
{
char *p = NULL;
allocateSpace(p);
printf("p1=%s\n", p);
}
void allocateSpace2(char **pp)
{
char *temp = malloc(100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
*pp = temp;
}
void test03()
{
char *p = NULL;
allocateSpace2(&p);
printf("p2=%s\n", p);
}
int main()
{
//test02();
test03();
system("pause");
return EXIT_SUCCESS;
}
这里char pp存储的是p指针的地址,这就是与上面那一种不同的地方。看pp=temp这句话,pp指的是找到**pp解引用之后的数据,解出来的数据是0x01指向的数据也就是NULL,然后将temp赋给pp,temp存的地址为0x001