🌺博客汇总:🌃Summary And Schedule🌠

🌸考研相关内容汇总:考研Schedule&&Summary

🌼408王道C督学课程目录:《王道C语言督学班目录》

本章需要掌握一些代码,就是简单的指针逻辑

  • 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; //间接访问得到变量i
}
//指针的传递
int main()
{
int i=10;
printf("before change i=%d \n",i);
change(&i); //传递变量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));//这里写a[i]等价的
printf("\n-----------------\n");
p=&a[4];//指针变量p指向了数组的最后一个元素
for(int i=0;i<N;i++)
{
printf("%3d",*(p-i));//这里写a[i]等价的
}
printf("\n-----------------\n");
char c[10]="hello";
char* d = c;
*d='H';
d[1]='E';//*(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);//使用malloc 动态申请堆空间
strcpy(p, "malloc success");
puts(p);
free(p);//free 时必领使用 malloc 申请时返回的指针值,不能进行任何偏移
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);//只有free时,堆空间才会释放
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>
//在子函数中去改变main函数中某个变量的值

void change(int *j)//j=&i
{
*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);//清除标准输入缓冲区中的\n
char *p;
p=(char*)malloc(n);//申请n个字节大小的空间,强制类型转换为char*
gets(p);//可以使用fgets(p,n,stdin); gets被去掉是因为不安全,会访问越界
puts(p);
return 0;
}