C 语言简明笔记

来源:互联网 发布:linux大棚命令百篇pdf 编辑:程序博客网 时间:2024/04/30 11:03

Chapter 1 快速入门

1.1 快速开始


    这个简单的例子有助于你快速进入C的世界:
#include <stdio.h>
#include 
<stdlib.h>

#define PI 3.1415926
float circle(float r);

int main(int argc, char* argv) {
    
float r =0.5;
    
float c=circle(r);
    printf(
"Hello,C world! ");
    printf(
"Circle is : %1.4f ", c);
    
    
//system("pause");
    
    
return 0;
}


float circle(float r) {
    
return PI*r*2;
}
 

    这个例子包含如下知识点:
  • 如何编写程序的入口点main函数
  • 如何用宏定义常量
  • 如何声明和定义函数
  • 如何调用函数
  • 如何用printf函数打印字符串和浮点数

2.2 字符串的表示,头文件

    这个例子显示了如何定义字符串和用头文件分离接口与实现:
//quick.h
#ifndef QUICK_H_
#define QUICK_H_

int len(char s[]);

#endif 
/*QUICK_H_*/
//quick.c
#include "quick.h"

int len(char s[]){
    
int c=0;
    
while(s[c]!='')c++;
    
return c;
}


//quickstart.c
#include 
<stdio.h>
#include 
<stdlib.h>

int len(char s[]){
    
int c=0;
    
while(s[c]!='')c++;
    
return c;
}


int main(int argc, char* argv) {
    
    
char s1[]="Nice weekend,";
    
char s2[]={'D','i','e','g','o','!',''};
    
char* ps="What can I do for you?";
    
    printf(
"%s%s%s ",s1,s2,ps);
    printf(
"Length of s1 is:%d ",len(s1));
    printf(
"Length of s2 is:%d ",len(s2));
    
    
//system("pause");
    
    
    
return 0;
}

    这个例子包含如下知识点:
  • 可以用三种方式定义字符串.技术上说,"字符串"保存在字符数组中,末尾必须有一个字符串结束符'/0'.如果字符串用双引号进行定义,则编译器会自动加上结束符.如果用单引号方式定义则需要手动加结束符.
  • 数组方式和指针方式都能定义字符串.但稍有区别.以后会对此进行说明.
  • 判断字符串长度的技术.从程序可以看出,如果字符串初始化不正确(末尾没有结束符),则函数有出错的可能.许多C中的Bug都来自于不正确的字符串操作.
  • 如何用头文件使函数的接口和实现分离.extern 告诉编译器该函数在某处存在定义,从而顺利进行编译.


2.3 类型转换

    这是个字符串到数值的转换例子
#include <stdio.h>
#include 
<stdlib.h>


int isdigit(char s);
int stringToInt(char s[]);

int main(int argc, char* argv) {
    
    
char s1[]="12345";
    
char s2[]="123s4at5";

    printf(
"1:Converted : %d ",stringToInt(s1));
    printf(
"2:Converted : %d ",stringToInt(s2));
    
    
//system("pause");
    return 0;
}


int isdigit(char s){
    
return (s>='0' && s<='9');
}


int stringToInt(char s[]){
    
int i,n;
    n
=0;
    
for(i=0;isdigit(s[i]);i++){
        n
=10*n+(s[i]-'0');
    }

    
return n;
}


    这里的知识点如下:
  • 如何判断字符是否一个数字.技术上通过ASCII码值来判断.
  • 如何应用这个特性转换字符.
    类型转换函数会在后续章节进行汇总.

2.4 指针

    这是一个老生常谈的话题了.函数内的参数(即形参)的改变并不影响实参的值,除非使用指针.
#include <stdio.h>

void failSwap(intint);
void swap(int*int*);

int main() {
    
int a=5, b=10;
    failSwap(a, b);
    printf(
"1.After failSwap(int,int),a is %d and b is %d ", a, b);
    swap(
&a, &b);
    printf(
"2.After swap(int,int),a is %d and b is %d ", a, b);

    
return 0;
}


void failSwap(int a, int b) {

    
if (a<b) {
        
int c=a;
        a
=b;
        b
=c;
    }

}



void swap(int* a, int* b) {
    
if (*a<*b) {
        
int c=*a;
        
*a=*b;
        
*b=c;
    }

}


 

    知识点
  • 指针的语法和使用

原创粉丝点击