8.数组指针和指针数组(2):
(1)指针数组:
int *a[5];
char *str[5];
指针数组主要用来操作字符串数组,通过将指针数组的每个元素存放字符串的首地址实现对多个字符串的操作
二维数组主要用来存储字符串数组,通过每行存储一个字符串,多行存储多个字符串所组成的数组
(2)指针和二维数组的关系:
int a[2][3] = {0};
int *p = NULL;
int (*q)[3] = NULL;
p = &a[0][0];
p = a[0];
p = *a;
q = a;
二维数组的数组名是指向数组第一行元素的数组指针
访问二维数组第m行第n的方式:
a[m][n]
*(a[m]+n)
*(*(a+m)+n)
*(p+m*N+n)
*(*(q+m)+n)
*(q[m]+n)
q[m][n]
#include <stdio.h>int main(void)
{int a[2][3] = {1, 2, 3, 4, 5, 6};int *p = NULL;int (*q)[3] = a;p = a[0];printf("&a[0][0]:%p\n", &a[0][0]);printf("&a[0][1]:%p\n", &a[0][1]);printf("&a[0][2]:%p\n", &a[0][2]);printf("&a[1][0]:%p\n", &a[1][0]);printf("&a[1][1]:%p\n", &a[1][1]);printf("&a[1][2]:%p\n", &a[1][2]);printf("\n");printf("a[0]:%p\n", a[0]);printf("a[0]+1:%p\n", a[0]+1);printf("a[1]:%p\n", a[1]);printf("a[1]+1:%p\n", a[1]+1);printf("\n");printf("a:%p\n", a);printf("a+1:%p\n", a+1);printf("\n");printf("*(a[1]+1):%d\n", *(a[1]+1));printf("*(*(a+1)+1):%d\n", *(*(a+1)+1));printf("\n");printf("*(p+1*3+1):%d\n", *(p+1*3+1));printf("\n");printf("*(*(q+1)+1):%d\n", *(*(q+1)+1));printf("\n");printf("*(q[1]+1):%d\n", *(q[1]+1));printf("\n");printf("q[1][1]:%d\n", q[1][1]);return 0;
}
二维数组传参:
int a[2][3] = {0};
int Fun(int (*parray)[3], int len);
char str[5][32] = {0};
int Fun(char (*pstr)[32], int len);
(3)二级指针:
1.指针数组传参时
int *a[5] = {NULL};
a: int **
char *pstr[5] = {"hello", "world", "how", "are", "you"};
int Fun(char **ppstr, int len)
#include <stdio.h>int main(void)
{int Num = 0;int *p = NULL;int **q = NULL;p = &Num;q = &p;printf("&Num: %p\n", &Num);printf("&p: %p\n", &p);printf("&q: %p\n", &q);printf("\n");printf("q = %p\n", q);printf("p = %p\n", p);printf("Num = %d\n", Num);printf("\n");printf("*q = %p\n", *q);printf("*p = %d\n", *p);printf("\n");printf("**q = %d\n", **q);return 0;
}
作业:
1.现有二维数组 char str[5][32] = {"hello", "world", "how", "are", "you"};
封装函数实现对所有字符串的排序
封装函数实现对所有字符串的打印
2.现有指针数组 char *pstr[5] = {"hello", "world", "how", "are", "you"};
封装函数实现对所有字符串的排序
封装函数实现对所有字符串的打印