本章需要掌握一些代码,就是简单的指针逻辑
- 1、如何定义一个指针,并用于构造函数,实现值传递
- 2、指针的偏移(指针指向一个数组后,指针+1代表指向元素+1,可以修改p=&a[3]指向第四个元素)
- 3、malloc一个空间,用strcpy、puts测试并free掉(malloc在 <stdlib.h>库)
1、指针的定义
本质:间接访问(指针p是指是一个地址值,*p是取其值)
1 2 3 4 5 6 7 8 9 10
| #include <stdio.h>
int main() { int i = 5; int* p = &i; printf("i=%d\n",i); printf("*p=%d\n",*p); return 0; }
|
2、值传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> void change(int* j) { *j=5; }
int main() { int i=10; printf("before change i=%d \n",i); change(&i); printf("after change i=%d \n", i); return 0; }
|
3、指针的偏移
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <stdio.h> #define N 5
int main() { int a[N]={1,2,3,4,5}; int *p = a; for(int i=0;i<N;i++) printf("%3d",*(p+i)); printf("\n-----------------\n"); p=&a[4]; for(int i=0;i<N;i++) { printf("%3d",*(p-i)); } printf("\n-----------------\n"); char c[10]="hello"; char* d = c; *d='H'; d[1]='E'; *(d+2)='E'; puts(c); return 0; }
|
4、指针与malloc动态内存申请,堆和栈的差异
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ int size; char *p; scanf("%d",&size); p=(char*)malloc(size); strcpy(p, "malloc success"); puts(p); free(p); printf("free success \n"); return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include <stdio.h> #include <stdlib.h> #include <string.h>
char* print_stack() { char c[100]="I am print_stack func"; char *p; p=c; puts(p); return p; }
char *print_malloc() { char *p=(char*)malloc(100); strcpy(p,"I am print malloc func"); puts(p); return p; }
int main() { char *p; p=print_stack(); puts(p); p=print_malloc(); puts(p); free(p); return 0; }
|
🌺5、OJ作业
网站:http://oj.lgwenda.com/
1、指针计算(change-value)
描述:输入一个整型数,存入变量i,通过子函数change把主函数的变量i除2,然后打印i,例如如果输入的为10,打印出5,如果输入的为7,打印出3
输入:一个整型数
输出:对应整型数除2后的商
🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <stdio.h>
void change(int *j) { *j=*j/2; }
int main() { int i; int *p=&i; scanf("%d",p); change(p); printf("%d\n",*p); return 0; }
|
2、申请空间(malloc)
描述:输入一个整型数,然后申请对应大小空间内存,然后读取一个字符串(测试用例的字符串中含有空格),字符串的输入长度小于最初输入的整型数大小,最后输出输入的字符串即可(无需考虑输入的字符串过长,超过了内存大小);
输入:一个整型数和一个字符串,例如
10
hello
输出:输出输入的字符串,上面输入的是hello,那么输出hello
🌺🌺🌺题解ヾ(^▽^)ゞ🌼🌼🌼
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> #include <stdlib.h>
int main() { int n; scanf("%d",&n); char c; scanf("%c",&c); char *p; p=(char*)malloc(n); gets(p); puts(p); return 0; }
|