介绍
空指针(null pointer)是指不指向任何内存地址的指针。在 C 编程中,空指针由常量 NULL 表示,该常量定义在头文件 stdio.h 中。使用空指针可以帮助避免错误,并为 C 程序增加功能。
在本实验中,你将学习空指针及其在 C 编程中的使用方法。你将创建一个程序,使用空指针在数组中搜索名称。
注意:你需要自己创建文件
~/project/main.c来练习编码,并学习如何使用 gcc 编译和运行它。
cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main
声明空指针
在 C 编程中,空指针是指不指向任何内容的指针。要声明一个空指针,可以将值 NULL 赋值给指针变量。
#include <stdio.h>
int main() {
int *ptr = NULL; // ptr 是一个空指针
return 0;
}
声明 void 指针
void 指针是一种没有特定类型的指针。它可以用来指向任何类型的数据。要声明一个 void 指针,在星号(*)前使用关键字 void。
在解引用(dereferenced)或用于指针算术运算之前,void 指针必须被类型转换为(cast to)另一种数据类型。
#include <stdio.h>
int main() {
int n = 10;
void *ptr = &n; // ptr 是一个指向 int 的 void 指针
printf("Value of n: %d\n", *(int*)ptr); // 在解引用前转换为 int 指针
return 0;
}
使用空指针标记指针数组的结尾
在 C 编程中,你可以使用空指针来标记指针数组的结尾。这在数组中搜索名称或其他数据时非常有用。
#include <stdio.h>
#include <string.h>
int search(char *ptr[], char* name);
char *names[] = {
"John",
"Peter",
"Thor",
"Chris",
"Tony",
NULL
};
int main(void)
{
if(search(names, "Peter") != 1)
{
printf("Peter is in the list.\n");
}
if(search(names, "Scarlett") == -1)
{
printf("Scarlett not found.\n");
}
return 0;
}
// 定义搜索函数
int search(char *ptr[], char*name)
{
for(int i=0; ptr[i]; ++i)
{
if(!strcmp(ptr[i], name))
{
return i;
}
}
return -1; // 未找到名称
}
自定义程序以支持用户输入
你可以自定义程序,允许用户输入名称到数组中并搜索名称。这可以通过 C 编程中的 scanf() 函数实现。
#include <stdio.h>
#include <string.h>
#define MAX_NAMES 100
int search(char *ptr[], char* name);
int main(void)
{
char *names[MAX_NAMES];
char name[50];
int count = 0;
printf("输入名称(按回车键结束):\n");
// 从用户输入获取名称
while(1)
{
scanf("%s", name);
if(strcmp(name, "") == 0)
{
break;
}
names[count] = (char*) malloc(strlen(name)+1);
strcpy(names[count], name);
count++;
}
names[count] = NULL; // 使用空指针标记数组结尾
// 搜索名称
while(1)
{
printf("输入要搜索的名称(按回车键结束):\n");
scanf("%s", name);
if(strcmp(name, "") == 0)
{
break;
}
int index = search(names, name);
if(index != -1)
{
printf("%s 在索引 %d 中找到。\n", name, index);
}
else
{
printf("%s 未找到。\n", name);
}
}
return 0;
}
// 定义搜索函数
int search(char *ptr[], char*name)
{
for(int i=0; ptr[i]; ++i)
{
if(!strcmp(ptr[i], name))
{
return i;
}
}
return -1; // 未找到名称
}
总结
在本实验中,你学习了空指针及其在 C 编程中的使用方法。你了解了如何声明空指针和 void 指针,以及如何使用空指针来标记指针数组的结尾。你还学习了如何自定义程序以支持用户输入,并使用空指针搜索名称。通过在程序中使用空指针,你可以使程序更加健壮,并避免常见的错误。



