一、指针数组和数组指针:
1、下题判断输出:
char str1[] = "hello world";
char str2[] = "hello world";
const char* str3 = "hello world";
const char* str4 = "hello world";
if (str1 == str2)
printf("str1 与 str2 相同\n");
else
printf("str1 与 str2 不同\n");
if (str3 == str4)
printf("str3 与 str4 相同\n");
else
printf("str3 与 str4 不同\n");
//输出结果为str1 != str2 str3 == str4 为什么?
char str1[]定义的是数组,需要为数组开辟空间,所以str1和str2分别指向各自数组的地址
const char* str3定义的是常量字符串,不能被改变,所以str3和str4同为指针指向同一个地址
2、指针数组和数组指针区别
指针数组
int* arr[2]; //存放指针的数组
数组指针
int arr[10] = { 1, 2, 3, 4, 5 };
int(*parr)[10] = &arr; //定义数组指针
//parr就是数组指针
double* d[5]; //这里是指针数组
double* (*pd)[5] = &d; //这里是数组指针
指针数组和数组指针中都存放的是指针
但是数组指针存放的只能是指向目标数组每一位位置的指针
指针数组可以存放任意值
3、arr表示数组首元素的地址,&arr表示的是整个数组为单位
验证:
int arr[10] = {0};
int *p1 = arr;
int(*p2)[10] = &arr;
printf("%p\n", p1);
printf("%p\n", p1 + 1); //这里跳过4个字节输出
printf("%p\n", p2);
printf("%p\n", p2 + 1); //这里跳过40个字节输出
4、数组名是数组首元素的地址
但是有两个例外:
(1).sizeof(数组名),数组名表示整个数组
(2).&数组名 - 数组名表示整个数组
5、数组指针通常使用在多维数组中
数组指针打印二维数组:
int arr[3][5] = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
Print(arr, 3, 5);
void Print(int(*p)[5], int r, int c)
{
int i = 0;
int j = 0;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d ", *(*(p + i) + j)); //首先对p+i解引用
} //再对该地址与该行第j个元素的和解引用即可得到目标值
printf("\n");
}
}
二、数组传参方式(以下写法均可行)
1、一维数组传参:
int arr[10] = { 0 };
int *arr2[5] = { 0 };
test(arr);
test2(arr2);
void test(int arr[])
{}
void test(int arr[10])
{}
void test(int* arr)
{}
void test2(int *arr[5])
{}
void test2(int **arr)
{}
2、二维数组传参:
int arr3[3][5] = { 0 };
test3(arr3);
void test3(int arr3[3][5])
{}
void test3(int arr3[][5])
{}
void test3(int (*arr3)[5])
{}