2

进阶指针_wx630c8eb20b5ff的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15770447/5754919
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

进阶指针_wx630c8eb20b5ff的技术博客_51CTO博客

wx630c8eb20b5ff 2022-10-14 00:22:15 ©著作权

文章标签 数组 字符串 指针数组 文章分类 其它 其它 阅读数143

p指向的arr的首地址,%s打印字符串,遇到‘\0’停止,两者打印效果相同。

int main()

{

char arr[] = "abcdef";

char* p = arr;

printf("%s\n", arr);

printf("%s\n", p);

return 0;

}

const char* p="abcdef";

常量字符串,p存的是首字符。*p不能够被更改。


const char* p1 = "abcdef";
const char* p2 = "abcdef";

p1和p2存储的字符串相等,所以用的一份空间。

p1改变时,p2不会应为p1改变而改变。


!!指针数组!!

指针数组是数组

int arr[] = { 0 };//整形数组
int ch[] = { 0 };//字符数组
int* parr[2];//存放指针的数组
char* pch[2];//存放指针的数组

数组从0开始计数,

int main()
{

int arr1[] = { 1,2,3 };
int arr2[] = { 3,4,5 };
int i;
int* a [] = {arr1,arr2};
for (i = 0; i < 2; i++)
{
int j;
for (j = 0; j < 3; j++)
{
printf("%d", a[i][j]);//打印所有数
}
printf("\n");
}
return 0;
}

!!数组指针!!

数组指针是指针。

//[]优于*
int arr[3] = { 1,2,3 };
int(*p)[3] = &arr;//数组地址存起来
void print(int(*p)[2], int x, int y)
{
int i;
for (i = 0; i < x; i++)
{
int j;
for (j = 0; j < y; j++)
{
printf("%d", *(*(p + i)+j));//*(p + i)跳过i行
printf("%d", (*(p + i)[j]));//三者相等
printf("%d", (p [i][j]));
}
printf("\n");
}
}
int main()
{
int arr[3][2] = {1,2,3,4,5,6};
print(arr, 3, 2);
return 0;
}

数组传参,指针传参​

一维数组传参

void test1(int arr[10])//可以去掉数字或者用*arr代替
{}
void test2(int* arr[20])//可用int**arr代替,可以去数字
}
int main()
{
int arr1[10] = { 0 };
int*arr2[20] = { 0 };
test1(arr1);
test2(arr2);
return 0;
}

二维数组传参

void test1(int arr[][5])//可以去掉数字,用*arr代替
{}
void test1(int(*arr)[5])
{}
int main()
{
int arr1[3][5];//3可以不写
test1(arr1);
return 0;
}

二级指针传参

void test1(int**p)
{}
int main()
{
int n;
int* p = &n;
int** pp = &p;
test1(pp);
test1(&p);
return 0;
}

函数有地址

printf(“%p”,&add);//add可以去&
(*(void(*)())0)()

*(void(*)()指针函数,()0,强制转换0的地址为指针函数,最后调用地址为0的函数。

void(*signal(int ,void(*)(int)))(int);

进阶指针_数组

typedef void(*fu)(int);//简化
fu signal(int, fu);

数组指针运用

int add(int x, int y)
{
return x + y;
}

int main()
{
int (*pa)(int,int) = add;
printf("%d", (*pa)(2,3));
return 0;
}

 函数指针的数组

int add(int x, int y)
{
return x + y;
}
int did(int x, int y)
{
return x - y;
}
int mul(int x, int y)
{
return x * y;
}
int div(int x, int y)
{
return x / y;
}

int main()
{
int (*pa)(int,int) = add;

int(*parr[4])(int, int) = { add,did,mul,div };
int i;
for (i = 0; i < 4; i++)
{
printf("%d\n", parr[i](2, 3));
}
return 0;
}
  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:最大值

下一篇:学习历程


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK