zoukankan      html  css  js  c++  java
  • 字符数组char

     数组做sizeof的参数不退化,传递给strlen就退化为指针;
     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 //#define PE(x) printf("sizeof("); printf(#x") = %d
    ", sizeof(x))
     5 
     6 void func(char str[100])
     7 {
     8     printf("func(sizeof(str) = %d)
    ", sizeof(str));
     9 }
    10 int main()
    11 {
    12     char str[] = "hello";
    13     char *p = str;
    14     int n = 10;
    15     void *q = malloc(100);
    16 /*
    17     PE(str);
    18     PE(p);
    19     PE(n);
    20     */
    21     /*
    22     char [],字符数组,OS自动在字符数组末尾追加'',
    23     作为字符数组大小的一部分,即占一个字节的内存。
    24     但是,并不作为字符数组有效长度的一部分。strlen是以''
    25     为标志。即char str[] = "hello",内存6,长度5
    26     */
    27     printf("sizeof(str) = %d
    ", sizeof(str));  //字符数组大小 sizeof(str) = 6
    28     printf("strlen(str) = %d
    ", strlen(str));  //
    29     printf("sizeof(p) = %d
    ", sizeof(p));      //一个指针的大小4个字节   sizeof(p) = 4
    30     printf("strlen(p) = %d
    ", strlen(p));      //
    31     printf("sizeof(*p) = %d
    ",sizeof(*p));     //第一个字符,sizeof(p) = 1
    32     printf("sizeof(n) = %d
    ", sizeof(n));      //sizeof(n) = 4
    33     char s[100];
    34     func(s);               //函数字符数组以头指针形式传递形参   sizeof(s) = 4
    35     printf("sizeof(*q=malloc(100)) = %d
    ", sizeof(p));//一个指针占4字节
    36     return 0;
    37 }
    sizeof(char [])

    定义字符数组时,系统会自动在末尾补上字符串结束标志字符'',并一起存到字符数组中,

    几点说明:

    ①字符串结束标志'\O'仅用于判断字符串是否结束,输出字符串时不会输出。

    ②在对有确定大小的字符数组用字符串初始化时,数组长度应大于字符串长度。如:

    char s[7]={ "program};

    由于数组长度不够,结束标志符'\O'未能存人s中,而是存在s数组之后的一个单元里,这可能会破坏其他数据,应特别注意。可以改为:

    char s[8]={ "program};

    strcpy()字符串str2中的\O也一起拷贝

    (4)字符串长度函数strlen()

    函数原型:unsigned int strlen(char *str);

    调用格式:strlen(字符串);

    函数功能:求字符串的实际长度(不包括'\O'),由函数值返回。例如:

    static char s[10]= "student";

    int len:

    len=strlen(s);

    len的值为7,而strlen("good")函数值为4。

  • 相关阅读:
    android测试开发环境搭建
    通过CMD命令行创建和使用Android 模拟器 AVD
    android 内存泄露测试
    NullPointerException检测
    iOS Automated Tests with UIAutomation
    命令方式重新签名apk
    Monkey log分析说明
    jQuery选择器总结[转]
    Java工程带库编译运行
    【转】从零开始学习Gradle之二---如何使用Task
  • 原文地址:https://www.cnblogs.com/sanghai/p/3397457.html
Copyright © 2011-2022 走看看