数组通过指针传入函数的示例
时间: 2023-03-26 12:03:47 浏览: 101
可以通过以下代码示例来演示数组通过指针传入函数:
```
#include <stdio.h>
void printArray(int *arr, int size) {
for(int i = ; i < size; i++) {
printf("%d ", *(arr + i));
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[]);
printArray(arr, size);
return ;
}
```
在这个示例中,我们定义了一个 `printArray` 函数,它接受一个指向整数数组的指针和数组的大小作为参数。在函数中,我们使用指针访问数组元素并打印它们的值。在 `main` 函数中,我们定义了一个整数数组 `arr`,并计算出它的大小。然后,我们调用 `printArray` 函数并将数组和大小作为参数传递。最后,我们返回 表示程序正常结束。
相关问题
c 数组结构体传入函数中
C语言中,可以通过传递指向数组或结构体的指针来在函数中操作这些数据类型。以下是传递数组和结构体指针的示例:
1. 传递数组指针:
```c
#include <stdio.h>
void printArray(int *arr, int size){
for(int i=0; i<size; i++){
printf("%d ", arr[i]);
}
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr)/sizeof(arr[0]);
printArray(arr, size);
return 0;
}
```
2. 传递结构体指针:
```c
#include <stdio.h>
struct Student{
char name[20];
int age;
};
void printStudent(struct Student *s){
printf("Name: %s\n", s->name);
printf("Age: %d\n", s->age);
}
int main(){
struct Student s = {"Tom", 18};
printStudent(&s);
return 0;
}
```
在上述示例中,使用指针传递数组或结构体可以减少内存复制的开销,提高程序效率。同时,传递指针还可以在函数内部修改数组或结构体的值,并保持这些更改在调用函数后依然有效。
结构体数组传入函数正确的实例
好的,下面是一个结构体数组传入函数的示例代码:
```c
#include <stdio.h>
// 定义结构体
struct Student {
char name[20];
int age;
float score;
};
// 定义函数,形参为结构体数组的指针和数组长度
void printStudents(struct Student *students, int len) {
for (int i = 0; i < len; i++) {
printf("name: %s, age: %d, score: %.1f\n", students[i].name, students[i].age, students[i].score);
}
}
int main() {
// 定义结构体数组
struct Student students[3] = {
{"Tom", 18, 89.5},
{"Jerry", 19, 78.0},
{"Mike", 20, 92.5}
};
// 调用函数,传入结构体数组的指针和数组长度
printStudents(students, 3);
return 0;
}
```
在这个示例中,我们定义了一个结构体 `Student`,包含学生的姓名、年龄和成绩。然后我们在 `main` 函数中定义了一个包含三个学生信息的结构体数组 `students`。接着我们通过调用函数 `printStudents` 将结构体数组的指针和数组长度传入函数中,函数中使用指针方式来访问结构体数组中的元素,最后输出学生的信息。
需要注意的是,在传递结构体数组时,可以直接传递数组名,因为数组名代表了数组的首地址,也就是结构体数组的指针。因此,在函数声明中,可以将结构体数组的形参声明为结构体指针类型。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)