目录
笔试题1
笔试题2
笔试题3
笔试题1
代码演示:
#include<stdio.h>
#include<string.h>
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test()
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf("%s\n", str);
}
int main()
{
Test();
return 0;
}
问:
运行 Test 函数会有怎样的结果?是否能正常运行 "hello world" 字符串?
代码解析:
Test 函数中创建了 char* 变量 str ,并赋值为空,将 str 值传递给 GetMemory 函数,GetMemory 函数创建临时指针变量 p 用来接收,并让 p 指向 malloc 动态开辟的 100 个字节的空间,回到 Test 函数后 str 还是空指针,GetMemory 函数并没有改变 str 的指向,所以 strcpy 函数运行时必然会报错,因为要对 str 指针解引用,这就是对空指针解引用操作,程序会直接崩溃
代码验证:
笔试题2
代码演示:
char* GetMemory()
{
char p[] = "hello world";
return p;
}
void Test()
{
char* str = NULL;
str = GetMemory();
printf("%s\n", str);
}
int main()
{
Test();
return 0;
}
问:
现在这个代码运行的结果是什么,为什么?
代码解析:
GetMemory 函数创建了一个 char 类型的数组 p ,并存储了 "hello world" 字符串, 最后将 p 这个首地址返回,但是数组 p 的生命周期只在进入 GetMemory 函数时创建,运行完 GetMemory 函数时结束,也就是将 p 数组所存储的空间还给了操作系统,但是 p 是指向这块空间的起始地址,赋值给 str 指针后打印,那么打印的结果只能是随机字符
代码验证:
笔试题3
代码演示:
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test()
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello world");
printf("%s\n", str);
}
int main()
{
Test();
return 0;
}
问:
代码是否能正常运行,为什么?
代码解析:
str 址传递给 GetMemory 函数,并开辟了 100 个字节的动态空间,在用 strcpy 函数将 "hello world" 字符串拷贝到 str 指向的动态空间中,最后再打印
代码验证: