在 C 语言中,除了结构体,还有多种数据类型可以通过指针传递给函数,以下为你详细介绍:
1. 基本数据类型
整数类型
像 int
、short
、long
等整数类型都能通过指针传递给函数。这种方式常用于函数需要修改调用者中整数变量的值。
收起
c
#include <stdio.h>
// 函数接收 int 指针,将其指向的值加 5
void addFive(int *num) {
*num += 5;
}
int main() {
int number = 10;
addFive(&number);
printf("修改后的数值: %d\n", number);
return 0;
}
浮点类型
float
和 double
等浮点类型也可以通过指针传递。例如在函数中修改一个浮点数的值。
收起
c
#include <stdio.h>
// 函数接收 double 指针,将其指向的值乘以 2
void multiplyByTwo(double *num) {
*num *= 2;
}
int main() {
double value = 3.14;
multiplyByTwo(&value);
printf("修改后的数值: %.2f\n", value);
return 0;
}
字符类型
char
类型同样能通过指针传递,常用于函数需要修改字符变量的值或者处理字符数组。
收起
c
#include <stdio.h>
// 函数接收 char 指针,将其指向的字符转换为大写
void toUpperCase(char *ch) {
if (*ch >= 'a' && *ch <= 'z') {
*ch -= 32;
}
}
int main() {
char letter = 'b';
toUpperCase(&letter);
printf("转换后的字符: %c\n", letter);
return 0;
}
2. 数组
数组名本质上是数组首元素的地址,所以可以直接将数组名(也就是数组指针)传递给函数。函数可以对数组元素进行读取、修改等操作。
收起
c
#include <stdio.h>
// 函数接收 int 数组指针和数组大小,计算数组元素的总和
int sumArray(int *arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int array[] = {1, 2, 3, 4, 5};
int size = sizeof(array) / sizeof(array[0]);
int result = sumArray(array, size);
printf("数组元素的总和: %d\n", result);
return 0;
}
3. 字符串
字符串在 C 语言中是以字符数组的形式存在的,通常用 char *
指针来表示。可以将字符串指针传递给函数进行字符串处理,如查找、替换、复制等操作。
收起
c
#include <stdio.h>
#include <string.h>
// 函数接收字符串指针,返回字符串的长度
int getStringLength(char *str) {
return strlen(str);
}
int main() {
char str[] = "Hello, World!";
int length = getStringLength(str);
printf("字符串的长度: %d\n", length);
return 0;
}
4. 枚举类型
枚举类型也可以通过指针传递给函数。这样函数可以修改枚举变量的值或者根据枚举值进行不同的操作。
收起
c
#include <stdio.h>
// 定义一个枚举类型
enum Color { RED, GREEN, BLUE };
// 函数接收枚举类型指针,将其指向的值修改为下一个枚举值
void nextColor(enum Color *c) {
*c = (*c + 1) % 3;
}
int main() {
enum Color currentColor = RED;
nextColor(¤tColor);
printf("下一个颜色的枚举值: %d\n", currentColor);
return 0;
}
5. 指针类型
可以将指针类型的数据再通过指针传递给函数,也就是传递指针的指针。这种方式常用于函数需要修改调用者中的指针变量本身。
收起
c
#include <stdio.h>
#include <stdlib.h>
// 函数接收 int 指针的指针,动态分配内存并初始化指针
void allocateMemory(int **ptr) {
*ptr = (int *)malloc(sizeof(int));
if (*ptr != NULL) {
**ptr = 100;
}
}
int main() {
int *p = NULL;
allocateMemory(&p);
if (p != NULL) {
printf("动态分配内存后的值: %d\n", *p);
free(p);
}
return 0;
}