二维数组 字符串和指针

指针+1移动了相当于所指向类型的大小的字节

int *s1[100]
移动了4个字节

int (*s2)[100]
移动了400个字节

char *s3  
移动了1 个字节

int *s4
移动了4个字节


***p2如何理解?

 int *p0 = &i
 *p0  = i

int **p1 = &p0
**p1 = i

int ***p2 = &p1
***p2 = i

*p2 = p1的值
**p2 = p0的值
***p2 = i的值

所以***p2就是p0的值        而p0的值最后指向了p2的地址
即***p2指向了p2的地址


二维数组  +   数组指针  +  二级指针
  1. int a[3][4] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } };//二维数组
  2. int(*p)[4] = a; //数组指针
  3. printf("%d\n", p); //8322788 这是个第一行的行地址,类似于二级指针
  4. printf("%d\n", *p); //8322788 这是个第一行第一列的地址
  5. printf("%d\n", **p); //0 这是第一个值

*(*(p+j)+i)  
p是第一行的行地址,
 二维数组里的 *(p+j)是个指针地址  



ps :参数里
二维数组等价于数组指针
二级指针等价于指针数组


二维数组传参:

按列优先打出来数组内容
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int a[3][4] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } };
  5. int(*p)[4] = a;
  6. for (int i = 0; i < 4;i++)
  7. {
  8. for (int j = 0; j < 3; j++)
  9. {
  10. printf("%d ",*(*(p+j)+i));
  11. }
  12. printf("\n");
  13. }
  14. return 0;
  15. }
二维数组传参要传两个维度


const:
如果不改变值,尽量使用const


回调函数:
把函数的指针作为一个函数的参数,叫做回调函数


strcpy :
  1. #include <stdio.h>
  2. #include <string.h>
  3. void str_cpy( char * dest , const char * src)
  4. {
  5. while(*dest++ = *src++);
  6. }
  7. int main()
  8. {
  9. char buf[100] = "aaaaaaaaaaaaaaaaaaaaaaaa"; //用来测试是否添加\0
  10. str_cpy(buf , "liuwei");
  11. printf("%s\n" , buf);
  12. return 0;
  13. }



strncpy:   
  1. #include <stdio.h>
  2. #include <string.h>
  3. void str_ncpy( char * dest , const char * src , int n)
  4. {
  5. while( (*dest++ = *src++) && n--);
  6. *(dest-1) = 0;
  7. }
  8. int main()
  9. {
  10. char buf[5] = "aaaa";;
  11. str_ncpy(buf , "liuweinihao" , 6);
  12. printf("%s\n" , buf);
  13. return 0;
  14. }



字符串和指针
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int i;
  5. char s[100] = "a刘威b";
  6. printf("%d\n", s[0]);
  7. printf("%d\n", s[1]);
  8. printf("%d\n", s[2]);
  9. printf("%d\n", s[3]);
  10. printf("%d\n", s[4]);
  11. printf("%d\n", s[5]);
  12. return 0;
  13. }


汉字由两个字节构成
192 245 是刘       
 -63  -11

205 254 是威     
  -51   -2

自己写一个strlen 类似 mb_strlen 汉字只算一个字符
  1. #include <stdio.h>
  2. #include <string.h>
  3. int mb_strlen(const char * p)
  4. {
  5. int len = 0;
  6. while( *p )
  7. {
  8. len++;
  9. if(*p++ < 0)
  10. p++;
  11. }
  12. return len;
  13. }
  14. int main()
  15. {
  16. char *s = "a我b是c你d大e";
  17. int len = mb_strlen( s );
  18. printf("%d\n",len);
  19. return 0;
  20. }






posted @ 2014-09-03 23:50  我爱背单词  阅读(320)  评论(0编辑  收藏  举报