Chinaunix首页 | 论坛 | 博客
  • 博客访问: 434721
  • 博文数量: 78
  • 博客积分: 2307
  • 博客等级: 上尉
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-04 00:31
个人简介

IT老鸟,信息安全硕士。

文章分类
文章存档

2017年(2)

2012年(21)

2011年(55)

分类: C/C++

2011-08-26 13:55:35

看了一些面试题。看起来挺晕的。今天自己实现了一个。出不来,就有了下面的笔记。
题目
编写一个函数,把char组成的字符串循环右移n位。比如原来是“abcdegfhi” n=2位移后是"hiabcdefg"
我直接翻答案。,又是strncpy又是memset又是memcpy,因为c语言复制从来都是从第一位开始复制。所以我看得直晕,没有办法首先该方法。
上题目:
//pStr是指向\0结尾的指针
//steps是要求移动的n
void moveloop(char *pStr,int steps){
//请填充
}
平台是vs2005
正确方法:
  1. // pointandarray.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include "stdio.h"
  5. #include "string.h"
  6. #include "process.h"
  7. void loopmove(char *pStr,int steps);
  8. int main()
  9. {
  10.     char pStr[]={'a','b','c','d','e','f','g','h','i'};
  11.     loopmove(pStr,2);
  12.     printf("pStr=%s",pStr);
  13.     system("pause");
  14.     return 0;
  15. }
  16. /**
  17. 草稿
  18. step=2 *pStr=hiabcdefg
  19. *pStr=abcdefg hiabcdefg hi

  20. */

  21. void loopmove(char *pStr,int steps){
  22.     int len=9;
  23.     char str[18];
  24.     for(int i=0;i<len*2;i++)
  25.         str[i]=*(pStr+(i%len));
  26.     char newstr[10];
  27.     for(int i=0,j=len-steps;j<len*2-steps;j++,i++)
  28.         newstr[i]=str[j];
  29.     newstr[9]='\0';
  30.     strcpy(pStr,newstr);
  31.     
  32.     }

下面是开始的时候我理解错了的方法。

main里面

 

  1. char *pStr=“agcdefghi”;
  2. 后面的完全一样。
  3. 除了strlen(pStr)的值等于9,而正确方法中我直接数出来的。

除了最后一个意外都正常。结果到了最后一个无论是strcpy还是strncpy还是memcpy都不行。加上\0也不行。

重新新建test项目

 

  1. // test.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include "string.h"
  5. #include "process.h"

  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8.     char *pStr"abcdefghi";
  9.     char newstr[]={'h','i','a','b','c','d','e','f','g'};
  10.     //strcpy(pStr,newstr);
  11.     *pStr='b';
  12.     printf("%s",pStr);
  13.     system("pause");
  14.     return 0;
  15. }

编译,报错。*pStr后面用双引号也不行。说const不能再次赋值。原来是const的问题。在char *里面默认是const类型的。而int *是可以改的。

int *的代码

 

  1. // pointandarray.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include "stdio.h"
  5. #include "string.h"
  6. #include "process.h"
  7. #define N 100
  8. void loopmove(char *pStr,int steps);
  9. int main()
  10. {
  11.     int x=1,y=2,z[10]={1,2,3,4,5,6,7,8,9,10};
  12.     int *ip;
  13.     ip=&x;//ip指向x
  14.     y=*ip;//y的值现在是1
  15.     printf("y=%d\n",y);
  16.     *ip=0;//x值现在是0
  17.     printf("x=%d\n",x);
  18.     ip=&z[0];//ip指向z[0]
  19.     printf("ip值现在是%d\n",*ip);
  20.     printf("z[5]=%d",*(ip+5));
  21.     system("pause");
  22.     return 0;
  23. }

 

下面是废话的时间了。简单来说在vs下面

int *p1;相对而言这个指针可以随便改。

char *p2;这个编译器默认为时const类型。我在vs下面也用的是cpp.

群里面就吵开了。说有的编译器是常量,有的不是常量,哪怕是const也能改。还有说编辑器相关。我还是看看卡卡西同学的帖子数组和指针的帖子吧。C语言果然很古怪。

阅读(1808) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~