针对考研的C语言学习(定制化快速掌握重点3)
1.数组常见错误
数组传参实际传递的是数组的起始地址,若在函数中改变数组内容,数组本身也会发生变化
#include<stdio.h>
void change_ch(char* str)
{str[0] = 'H';
}
int main()
{char ch[] = "hello";change_ch(ch);printf("%s\n", ch);return 0;
}
2.指针
指针变量加减法操作时,每次加一,增加的长度是其基类型的长度*1
#include<stdio.h>
int main()
{int i[] = { 1,2,3,4,5 };char ch[] = "hello";int* pInt = &i;char* pCh = &ch;printf("%d\n", *pInt);printf("*(pInt+1) == %d\n", *(pInt + 1));printf("%c\n", *pCh);printf("*(pCh+1) == %c\n", *(pCh + 1));return 0;
}
指针的另一种用法
#include<stdio.h>
int main()
{int i[] = { 1,2,3,4,5 };char ch[] = "hello";int* pInt = &i;char* pCh = &ch;printf("%d\n", pInt[0]);printf("%c\n", pCh[0]);return 0;
}
这种用法称为“数组指针”(array pointer)或“指针算术”(pointer arithmetic):
pInt[0]
:等同于*(pInt + 0)
,实际上获取的是i[0]
的值,即1
。pCh[0]
:同样等同于*(pCh + 0)
,获取的是ch[0]
的值,即字符'h'
。
这利用了 C 语言中指针和数组的关系,允许通过数组下标语法来访问指针指向的内容。
3.引用
下节继续