c primer plus----第11章 字符串和字符串函数(一)

11.1.1 在程序中定义字符串
    1.使用字符串常量
    2.char数组
    3.char指针
    4.字符串数组

//11.1
//字符串是以空字符串\0结尾的char数组
//gets() puts()的使用
#include <stdio.h>
#define MSG "You must have many talents.Tell me some."

#define LIM 5
#define LINELEN 81

int main(void)
{
    char name[LINELEN];
    char talents[LINELEN];
    int i;

    //定义字符串的5种方法
    //#define MSG "You must have many talents.Tell me some."
    const char m1[40] = "Limit yourself to one line worth.";
    const char m2[] = "if you can not think of anything ,fake it.";
    const char *m3 = "\nEnough about me - what is your name?";
    //错误:const char *m4[] = "\nEnough about me - what is your name?";

    const char *mytal[LIM] = {
            "Adding numbers swiftly",
            "Multiplying accurately", "Stashing data",
            "Following instructions to the letter",
            "Understanding the C language"
            };

    printf("Hi! I am Clyde the Computer." "I have many talents.\n");

    printf("Let me tell you some of them.\n");
    puts("What were they? here is a partial list.");

    for(i = 0; i < LIM; i++)
        puts(mytal[i]);

    puts(m3);

    gets(name);

    printf("Well, %s, %s\n", name, MSG);
    printf("%s\n%s\n", m1, m2);
    gets(talents);

    puts("Let see if i have got that list:");
    puts(talents);

    printf("Thanks for the information, %s.\n", name);

    return 0;
}

一.字符串常量(字符串文字)
    1.双引号里面的字符加上编译器自动提供的结束标志\0字符。
    2.#define也可以用来定义字符串常量。
    3.下面相等:
      char greeting[50] = "Hello " "World!";
      char greeting[50] = "Hello World!";
    4.字符串是静态存储类。
      静态存储是指如果在一个函数中使用字符串常量,即使是多次调用了这个函数,该字符串在程序的整个运行过程中只存储一份。
    5.整个引号中的内容作为指向该字符串存储位置的指针。和把数组名作为指向数组存储位置的指针类似。

//11.2
#include<stdio.h>
int main(void)
{
    printf("%s,%p,%c\n", "We", "are", *"coder!");
    //%p 字符串中第一个字符的地址
    //*"coder!" 指向地址中的值,字符串"coder!"中的第一个字符
    //We,0x80484fa,c
    return 0;
}

二.字符串数组及初始化
    1.const char m1[] = {'H','e','l','l','o','\0',};
      1)如果没有\0就是字符数组而不是字符串。
      2)编译器决定数组的大小。
    2.指定数组大小的时候,一定要确保数组元素比字符串长度至少多1,未被使用的元素被自动初始化为0。
    3.声明一个数组时,数组大小必须是整型常量,而不是运行的时候能够得到的变量的值。编译的时候数组的大小被锁定到程序中。
      int n = 8;
      char m2[n];//C99之后为变长数组,之前无效。
      char m3[2 + 5];//合法
    4.m1 == &m1[0];
      *m1 == 'H';
      *(m1 + 1) == m1[1]=='e';
    5.下面的两个都声明m3是一个指向给定字符串的指针。
      const char m3[] = "\nEnough about me - what is your name?";
      const char *m3 = "\nEnough about me - what is your name?";

 

posted on 2013-03-13 13:35  屁屁侠  阅读(256)  评论(0编辑  收藏  举报

导航