1.scanf函数
注意事项:
#include<stdio.h>
int main(){
int i = 10;
char a;
scanf("%d", &i);
printf("i = %d\n", i);
// fflush(stdin);
scanf("%c", &a);
printf("a = %c\n", a);
return 0;
}
把30赋给了i,然后\n给了字符a
#include<stdio.h>
int main(){
int i, ret;
char c;
float f;
ret = scanf("%d %c%f", &i, &c, &f);
printf("i = %d, c = %c, f = %5.2f\n", i, c, f);
printf("ret = %d", ret);
return 0;
}
特别注意:没有空格的情况
2.printf函数
#include<stdio.h>
int main(){
int i = 13;
float f = 3.14;
printf("i = %4d, f = %5.2f\n", i, f);//默认右对齐
printf("i = %-4d, f = %-5.2f\n", i, f);//在%后加负号左对齐
printf("i = %04d\n", i);//右对齐,不足两位用0填充
printf("%o\n", i);//8进制输出
printf("%X\n", i);//十六进制大写输出
printf("%x\n", i);//十六进制小写输出
printf("%#X\n", i);//十六进制大写标准输出
printf("%%\n");//输出百分号
return 0;
}
3.关系运算符
#include<stdio.h>
int main(){
int i = 5;
if(3 < i < 10)
printf("i在3到10间");
else
printf("i不在3到10间");//永远不会执行到这:3 < i < 10先执行3<5,结果为1
//然后1<10,永远为真
return 0;
}
4.gets函数与puts函数
5.一维数组
#include<stdio.h>
void print(int b[],int len)
{
int i;
for(i=0;i<len;i++)
{
printf("%3d",b[i]);
}
b[4]=20; //在子函数中修改数组元素
printf("\n");
}
#define N 5
int main()
{
int a[5]={1,2,3,4,5}; //定义数组时,数组长度必须固定
print(a,5);
printf("a[4]=%d\n",a[4]); //a[4]发生改变
return 0;
}
数组a的内存情况 :a的初始地址为0x61fe00
数组b的内存情况 :b的地址为:61fde0,b里的内容是61fe00,恰好是a的地址,也就是说,b指向a, 且b占8个字节
所以:
6.指针与动态申请
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *print_stack(){
char c[17] = "i am print_stack";//字符数组可以这样赋值,且与char *完全等价
puts(c);
return c;
}
char *print_malloc(){
char *p;
p = (char*)malloc(20);
strcpy(p, "i am print_malloc");
puts(p);
return p;
}
int main(){
char *p;
p = print_stack();//数据在栈空间
printf("p = %s\n", p);
p = print_malloc();//数据在堆空间
puts(p);
return 0;
}
原因:
7.结构体对齐
结构体的第一个成员总是存储在结构体变量开辟的空间的起始地址。
其它成员变量要存储在一个名叫对齐数的整数倍的地址。
结构体的大小必须是其最大成员的整数倍。
#include<stdio.h>
struct student1{
double score;
short age;
};//最大为8, short + 6 ==>16
struct student2{
double score;
int height;
short age;
};//最大为8, short + int + 2 ==>16:如果紧挨的两个数据类型<=最大的,则这两个可以合并
struct student3{
int height;
char sex;
short age;
};//最大为4, short + char + 1 ==>8
int main(){
printf("s1 size:%d\n", sizeof(student1));
printf("s2 size:%d\n", sizeof(student2));
printf("s3 size:%d\n", sizeof(student3));
}
8.typedef的使用
typedef struct student{
double score;
short age;
}s, *ps;
// s <==> struct student
// ps <==> struct student*
注意:当给结构体起别名时,struct 后面的student可以省略