用C语言写一直指针数组函数
时间: 2024-05-14 09:17:12 浏览: 13
好的,以下是用C语言写一直指针数组函数的示例代码:
```c
#include <stdio.h>
void function(int *arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *arr[i]);
}
}
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {4, 5, 6};
int *arr[] = {arr1, arr2};
function(arr, 2);
return 0;
}
```
上面代码中,我们定义了一个指针数组`arr`,该数组包含两个元素,每个元素都是一个整型数组的首地址。我们定义了一个名为`function`的函数,参数包括指针数组和其大小。该函数的作用是遍历指针数组,并输出每个整型数组的首元素值。在主函数中,我们传递了指针数组和其大小作为参数调用函数`function`,输出结果为`1 4`。
相关问题
定义一个C语言的函数指针数组
在C语言中,可以定义一个函数指针数组,用于存储一组函数指针,每个函数指针指向一个特定的函数。下面是一个示例:
```c
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
// 定义函数指针数组,存储指向三个不同函数的指针
int (*math_functions[3])(int, int) = {add, subtract, multiply};
int a = 10, b = 5;
// 使用函数指针调用相应的函数
printf("%d\n", math_functions[0](a, b)); // 输出 15
printf("%d\n", math_functions[1](a, b)); // 输出 5
printf("%d\n", math_functions[2](a, b)); // 输出 50
return 0;
}
```
在上面的例子中,我们定义了一个包含三个元素的函数指针数组 `math_functions`,每个元素都是一个指向函数的指针,分别指向 `add`、`subtract` 和 `multiply` 函数。然后我们使用函数指针数组来调用相应的函数,并传入两个整数参数。最后程序输出每个函数返回的结果。
c语言指针数组函数传递
在 C 语言中,指针数组是一种数组类型,其中每个元素都是一个指针。可以将指针数组作为函数参数传递,并在函数内部使用。
下面是一个示例,演示了如何将指针数组作为函数参数传递:
```c
#include <stdio.h>
#include <stdlib.h>
void printStrings(char *strings[], int count) {
for (int i = 0; i < count; i++) {
printf("%s\n", strings[i]);
}
}
int main() {
char *strings[] = {
"Hello",
"World",
"from",
"C",
};
int count = sizeof(strings) / sizeof(char *);
printStrings(strings, count);
return 0;
}
```
在上面的例子中,我们定义了一个指针数组 `strings`,其中每个元素都是一个指向字符数组的指针。我们还定义了一个 `printStrings` 函数,该函数接受一个指向指针数组的指针 `strings` 和一个整数 `count`,并在函数内部使用循环遍历指针数组,并打印每个字符串。在 `main` 函数中,我们创建了一个指针数组 `strings`,并计算了它的大小。然后,我们调用 `printStrings` 函数,并将指针数组 `strings` 和它的大小作为参数传递给该函数。
需要注意的是,由于指针数组本身是一个指针,因此在传递指针数组时,需要将其声明为指向指针数组的指针。因此,在上面的例子中,我们在 `printStrings` 函数中将指针数组声明为 `char *strings[]`,而不是 `char strings[][]`。