随笔 - 1  文章 - 0  trackbacks - 0
<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿

随笔档案

文章分类

文章档案

搜索

  •  

最新评论


the basic operate
一级指针的典型用法 : 数组 、 字符串

在C语言中使用字符数组来模拟字符串

C语言中的字符串是以’\0’结束的字符数组

C语言中的字符串可以分配于栈空间,堆空间或者只读存储区


字符和字符数组:

int main(int argc, char * * argv)
{
    char buf[120]= "hello";
    printf("%s", buf);

    char buf2[120] = {'h','e','l','l','o'};
    printf("%s" , buf2);
    
    char buf3[] = "world";
    printf("%d , %d" , strlen(buf3) , sizeof(buf3));
    return 0;
}


 数组或指针操作字符串
int main()
{
    char buf[10] = "hello";
    for(int i = 0; i<strlen(buf) ; i++ )
    {
        printf("%c" , buf[i]);
    }
    
    printf("\n");
    char * p = buf; //指向 buf[0]的地址不是数组!!! 
    for(int i = 0; i<strlen(buf); i++)
    {
        printf("%c", *(p+i));
    } 
    
    return 0;
//    hello
//    hello
}

buf[i] --> buf[0+i] --> *(buf+i)

中括号的本质:
buf5[10];
buf5 = buf5 + 1
buf5 是一个常量指针。编译器这么做的。

为什么这么做?
如果进行栈的内存回收 , 如果允许 常量指针buf5 修改地址 则很难在修改之后找到buf 的地址对这段内存进行析构。
为可保证 数组 这块内存首地址的安全 buf5 是一个常量 , 传到函数中也是常量指针地址不能轻易改变。
这就是为什么 指针 p = p+1; 可以 ; buf5 = buf5 +1;不可以;


字符串一级指针的内存模型图
int main()
{
    char buf[20] = "aaaaa";
    char buf2[] = "11111";
    
    char * p1 = "mmmmm";
    
    char * p2 = malloc(100);
    strcpy(p2,"222222"); 
    free(p2);
    
    return 0;
}



-----

字符串做函数参数

业务模型和测试案例分开:

void cpstr(char * p , char * q)
{
    for(; *p != '\0'; p++, q++  )
    {
        *q = *p;
//      *q++ = *q++;   先  *q = *p;  再 p++, q++
    }
    *q = '\0';
}
/* 改进不用手动添加  \0
   while( (*q = *p) !=0)
   {
      p++;
      q++;
   }
*/

/*
   while( (*q++ = *p++) !=0)
   {
      ;
   }
*/

/*
   while( (*q++ = *p++))
   {
      ;
   }
*/

int main()
{
    char * p = "helloworld";
    char dest[100];
    cpstr(p , dest);
    
    printf("dest: %s" , dest);
    return 0;
}

业务模型和测试案例未分开:
int main004()
{
    char from[] = "helloworld"; 
    char to[20];
    
    int i;
    for(i = 0; *(from+i) != '\0'; i++ )
    {
        *(to + i) = *(from+i);
    }
    to[i] = '\0';
    
    printf("%s\n" , from);
    printf("%s\n" , to);
    return 0;
}


改进代码
void cpstr(char * p , char * q)
{

//在形参中另存一份  辅助变量 不要轻易改变形参的值
   char * p = tmp_p;
   char * q = tmp_q;
      //所以不会影响主调用函数指针的指向。


    for(; *p != '\0'; p++, q++  )
    {
        *q = *p;
//      *q++ = *q++;   先  *q = *p;  再 p++, q++
    }
    *q = '\0';
}
/* 改进不用手动添加  \0
   while( (*q = *p) !=0)
   {
      p++;
      q++;
   }
*/

/*

   if( p ==NULL || q= NULL)
   {
         return -1;
   } //添加判断

   //  ->  while( (*q++ = *p++) !=0);

   while( (*q++ = *p++) !=0)
   {
      ;
   }
*/

/*
   while( (*q++ = *p++))
   {
      ;
   }
*/

int main()
{
    char * p = "helloworld";
    char dest[100];
    cpstr(p , dest);
    
    printf("dest: %s" , dest);
    return 0;
}


项目开发中的字符串模型


strstr _ while do_while





posted on 2017-07-13 12:58 silvercell 阅读(124) 评论(0)  编辑 收藏 引用 所属分类: c raise