1.计算机内部的存储机制
2.指针和变量
#include "stdio.h"
int main()
{
char a = 0x66;
char *p;
p = &a;
// 也可直接char *p = &a;
printf("%x\n",a); //返回16进制的66
printf("%x\n",p); //返回19f2c
printf("%x\n",*p);//返回66
p++;
printf("%x\n",p); //返回19ff2d
p--;
printf("%x\n",p); //返回19ff2c
return 0;
}
3.数组和指针
数组和结构体等就是地址,可不用加&,其他数据类型是助记符而不是地址所以要加&,如下:
#include "stdio.h"
int main()
{
char a[] = {0x33,0x34,0x35};
char *p;
p = a;
printf("a[0] = %x\n",a[0]);
printf("a[1] = %x\n",a[1]);
printf("a[2] = %x\n",a[2]);
printf("*p = %x\n",*p);
printf("*(p+1) = %x\n",*(p+1));
printf("*(p+2) = %x\n",*(p+2));
/*数组就是指针,所以可以直接用指针的方法表示数组
printf("*a = %x\n",*p);
printf("*(a+1) = %x\n",*(p+1));
printf("*(a+2) = %x\n",*(p+2));
*/
return 0;
}
用指针实现找数组中的最大值。
#include "stdio.h"
int f(int *b,int count)
{
int i,max = b[0];
for(i = 0;i < count;i++)
if(b[i] > max)
max = b[i];
return max;
}
int main()
{
int a[] = {11,2,3,4,21};
int Max = f(a,5);
printf("Max = %d\n",Max);
return 0;
}
若在被调用函数中改变了形参的值,则原数组的值也会发生改变,除非加上const,如下:
#include "stdio.h"
int f(int *b,int count)
{
int max = b[0];
b[1] = 66;
return max;
}
/*
int f(const int *b,int count)
{
int max = b[0];
b[1] = 66;
return max;
}
*/
int main()
{
int a[] = {11,2,3,4,21};
int Max = f(a,5);
printf("a[1] = %d\n",a[1]);
return 0;
}
用指针实现寻找数组中的最大值和最大值出现的次数:
#include "stdio.h"
void FindMaxAndCount(int *max,int *count,const int *b,int lenth)
{
int i;
*max = b[0];
*count = 1;
for(i = 1;i < lenth;i++)
{
if(b[i] > *max)
{
*max = b[i];
*count = 1;
}
else if(b[i] == *max)
{
(*count)++; // 注意这里要加括号
}
}
}
int main()
{
int a[] = {11,2,3,21,21};
int Max,Count;
FindMaxAndCount(&Max,&Count,a,5);
printf("Max = %d\n",Max);
printf("Count = %d\n",Count);
return 0;
}
4.函数和指针
#include "stdio.h"
int Time[] = {11,22,33};
int *GetTime(void)
{
// 不能将数组放进函数里,因为数组函数调用完成后函数会被销毁,
// 返回的是一个无意义的值,除非使用static 进行修饰
// static int Time[] = {11,22,33};
return Time;
}
int main()
{
int *pt;
pt = GetTime();
printf("pt[0] = %d\n",pt[0]);
printf("pt[1] = %d\n",pt[1]);
printf("pt[2] = %d\n",pt[2]);
return 0;
}