目录
一、简介
本文主要讲述指针、数组和数组指针等做为函数参数进行使用,最后通过具体示例进行快速理解,希望对大家有所帮助。
二、数组
2.1 一维数组
一维数组作为参数传参,直接将地址传进来进行使用。
#include <stdio.h>
#include <stdlib.h>
void func(int arr[]){
int i = 0;
for(i;i < 5;i++){
printf("the arr[%d] is :%d\n",i,arr[i]);
}
return;
}
void main(){
int arr[5] = {1,2,3,4,5};
func(arr);
return;
}
2.2 二维数组
相对于一维数组,二维数组要明确列的值,具体有下面两种类型:
第一类 固定行列传参 : void func(int arr[2][3])
第二类 固定列传参:void func(int arr[][3])
#include <stdio.h>
#include <stdlib.h>
//void func(int arr[2][3]){
void func(int arr[][3]){
int i ,j;
for(i = 0;i < 2;i++){
for (j=0;j < 3;j++){
printf("the arr[%d][%d] is :%d\n",i,j,arr[i][j]);
}
}
return;
}
void main(){
int arr[2][3] = {1,2,3,4,5,6};
func(arr);
return;
}
三、指针
3.1 一级指针
首先指针即存放一个地址,指向的这个地址的类型要根据具体数据进行声明;
如:
int a = 3;
int *p = &a; //将存放整型3的地址赋值给p
以指针数组为例进行解析:
#include <stdio.h>
#include <stdlib.h>
void func(int *p){
int i = 0;
for(i;i < 5;i++){
printf("the arr[%d] is :%d\n",i,*(p+i));
}
return;
}
void main(){
int arr[5] = {1,2,3,4,5};
int *p = arr; //arr为数组的首地址
func(p);
return;
}
3.2 二级指针
二级指针相对于一级指针的不同是,二级指针将一级指针的地址再存放在定义的二级指针中:
int a = 3;
int *p = &a; //将存放整型3的地址赋值给p,指向一个int数据
int **q = &p; //存放指针p的地址,指向一个指针
使用基本与一级指针类似,用于多级函数传参使用:
#include <stdio.h>
#include <stdlib.h>
void func(int **q){
int i = 0;
for(i;i < 5;i++){
printf("the arr[%d] is :%d\n",i,*(*q+i));
}
return;
}
void main(){
int arr[5] = {1,2,3,4,5};
int *p = arr; //arr为数组的首地址
int **q = &p;
func(q);
return;
}
注意:
当申明viod ** 类型的二级指针时,如果要输出,需要先强制转换为特定的类型进行输出,如 int **:
int d = 4;
void * f = (void*)&d;
void ** g = &f;
printf("the **g is :%d\n",**((int **)g));
3.3 结构体指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char *name;
int score;
struct student* next;
}stu,*stu1;
int main(){
stu.name = (char*)malloc(sizeof(char)); /*1.结构体成员指针需要初始化*/
strcpy(stu.name,"Jimy");
stu.score = 99;
stu1 = (struct student*)malloc(sizeof(struct student));/*2.结构体指针需要初始化*/
stu1->name = (char*)malloc(sizeof(char));/*3.结构体指针的成员指针同样需要初始化*/
stu.next = stu1;
strcpy(stu1->name,"Lucy");
stu1->score = 98;
stu1->next = NULL;
printf("name %s, score %d \n",stu.name, stu.score);
printf("name %s, score %d \n",stu1->name, stu1->score);
free(stu1);
return 0;
}
输出:
name Jimy, score 99
name Lucy, score 98