宏定义函数
#include<stdio.h>
#define OUT printf("helloworld\n")
#define P(s) printf("%s\n",s)
#define SQR(x) x*x //宏函数只是简单替换,注意优先级
/*
宏函数的优点:
1节省空间(不需要给形参分配空间)
2执行效率高(不需要根据地址找到函数的入口)
宏函数的缺点:
1编译效率低(第一步预处理需要替换)
2不安全,只是简单替换,没有语法检查
*/
int main()
{
int a=1,b=2;
OUT;
P("12345");
printf("%d\n",SQR(a+b));
return 0;
}
运行
[root@localhost 28]# ./7-宏函数
helloworld
12345
5
指针
#include<stdio.h>
int main()
{
printf("%d\n",sizeof(int *));
printf("%d\n",sizeof(char *));
printf("%d\n",sizeof(double *));//所有指针类型都占4个字节
int a=1;
int *p=&a;//指针p指向a
*p=100;//a=100,*取值
printf("a=%d\n",a);
char ch='a';
char *q=&ch;
*q='b';
printf("%c\n",ch);
//p=&ch; //类型不兼容
printf("p的地址:%p\n",p);
printf("q的地址:%p\n",q);
printf("p+1的地址:%p\n",p+1);
printf("q+1的地址:%p\n",q+1);
return 0;
}
运行
4
4
4
a=100
b
p的地址:0xbfb7b388
q的地址:0xbfb7b387
p+1的地址:0xbfb7b38c
q+1的地址:0xbfb7b388
指针赋值
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;//1.定义指针
//p=0x100;//段错误,访问了不能访问的内存,不能自己指定地址
int a;//操作系统分配的空间,合法的
p=&a;//2.给指针赋值,地址合法
*p=1;//第一种赋值法
int *q;//q是局部变量,未初始化的局部变量都是垃圾值,野指针不能使用
//*q=100;
int *z=NULL;//空指针,空指针也是不能使用
//*z=100;//段错误
int *pa=(int *)malloc(sizeof(int)*2);//第二种赋值法
if(NULL==pa)//若申请失败,返回NULL
{
printf("malloc failure!\n");
}
*pa=100;//填入malloc前四个字节
*(pa+1)=200;//填入malloc后四个字节
int i;
for(i=0;i<2;i++)
{
printf("%d ",pa[i]);
}
printf("\n");
return 0;
}
运行
[root@localhost 28]# ./9-指针赋值
100 200
指针和数组
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int a[5]={1,2,3,4,5};
int *p=a;
int i;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
//printf("%d ",a[i]);//下标访问数组元素
printf("%d ",*(p+i));//指针法访问数组元素
//printf("%d ",*(a+i));
}
printf("\n");
char *ptr=(char *)malloc(sizeof(char)*32);
strcpy(ptr,"helloworld");
//printf("%s\n",ptr)
for(i=0;i<10;i++)
{
printf("%c",ptr[i]);
}
printf("\n");
return 0;
}
运行
[root@localhost 28]# ./10-指针和数组
1 2 3 4 5
helloworld
字符串指定位置插入字符
#include<stdio.h>
#include<string.h>
int main()
{
int num;
char ch;
char str[32]={0};
printf("input:\n");
scanf("%s%d %c",str,&num,&ch);
printf("\n");
int length=strlen(str);
int i;
for(i=0;i<length-num+1;i++)
{
str[length-i]=str[length-1-i];
}
str[num-1]=ch;
printf("%s\n",str);
return 0;
}
运行
[root@localhost 28]# ./11-字符串指定位置插入字符
input:
helloworld 3 x
hexlloworld
(字符指针)数组的输出
#include<stdio.h>
int main()
{
char *string[]={"I love China!","I am"};
printf("%s ",*string);//输出第一个数组字符串
printf("%s\n",*(string+1));//输出第二个数组字符串
return 0;
}
运行
[root@localhost 28]# ./14-用字符串指针指向一个字符串
I love China! I am