C和指针读后笔记

来源:互联网 发布:工行淘宝联名储蓄卡 编辑:程序博客网 时间:2024/04/30 04:06

注释:

#if 0

statements

#endif

从逻辑上删除一段代码或者注释。
编程练习:编写一个程序,从标准输入读取几行输入。每行输入都要打印到标准输出上,前面要加行号。在编写这个程序时要试图让程序能处理的输入行的长度没有限制。

#include <stdio.h>


#include <stdlib.h>


int main()
{
int ch;
int line;
int at_beginning;


line = 0 ;
at_beginning = 1 ;
/*
**读取字符并逐个处理它们
*/
while ( (ch = getchar()) != EOF )//键盘输入EOF:ctrl+Z
{


if ( at_beginning == 1 )
{
at_beginning = 0 ;
line += 1 ;
printf("%d:",line);
}


//打印字符,并对结尾进行处理
putchar(ch) ;
if ( ch == '\n' )
{
at_beginning = 1 ;


}


      


}
return 0 ;
}


字符串常量:字符串常量实际上是个指针。
已知字符串常量"xyz" ,
"xyz"+1 代表:字符串中的第二个字符:y
*"xyz"代表:字符串的第一个字符:x
"xyz"[2]代表:字符串的第三个字符:z

(1)神秘的函数
//参数是一个0~100的值
#include <stdio.h>
void mystery(int n)
{
n += 5 ;
n /= 10 ;
printf( "%s\n" ,"**********" + 10 - n );
//字符串常量最后一个字符其实是'\0'.
}

参数为0 ,打印0个星号
参数为100,打印10个星号。

(2)putchar ("0123456789ABCDEF"[value%16] ) ;
10进制转换为16进制部分代码。



#include <stdio.h>


#include <stdlib.h>
#if 0
(1) 宏替换
#endif


//只有当字符串常量作为宏参数给出时才能使用。
#define PRINT(FORMART,VALUE) \
printf ( "The value is " FORMART "\n" , VALUE)


//#argument 这种结构被预处理器翻译为“argument”。
#define PRINT1(FORMART,VALUE) \
printf("The value of " #VALUE \
" is " FORMART "\n" , VALUE)




#if 0
(2) 宏与函数
宏是与类型无关的,有一些任务根本无法用函数实现。
#endif


#define MALLOC(n,type) \
( (type*)malloc( (n)*sizeof(type)) )


typedef struct Node
{


int number;
char ch ;
}Node;




#if 0
(3) 带副作用的宏
当宏参数在宏定义中出现的次数超过一次时,如果这个参数具有副作用,将会出现不可预料的结果。
#endif


#define MAX(a,b)  ( (a) > (b) ? (a) : (b) )


#if 0
(4) 防止头文件多重包含
#endif


#ifndef  _HEADERNAME_H
#define _HEADERNAME_H 1
/*
头文件中的内容
*/
#endif


int main()
{

int x= 3 ;
PRINT("%d",x*3);
PRINT1("%d",x*3);


Node *p = MALLOC(3,Node); //申请一个大小为3个Node的空间
p[2].number= 3;
p[2].ch='a';
PRINT("%d",p[2].number);
PRINT("%c",p[2].ch);




int a = 5 ;
int b = 6 ;
int c = MAX(a++,b++);
PRINT1("%d",a);//6
PRINT1("%d",b);//8
PRINT1("%d",c);//7


return 0 ;
}



(1)调试用的printf,后应该加fflush(stdout),立即输出到屏幕上,因为printf结果是先写入缓冲区中。

0 0
原创粉丝点击