2014-02-26 40 views
0

我有不断增加的字符,所以它会显示在ascci代码中的下一个字符的功能,但我的问题是,它从来没有打破循环C++字符数组空字符while循环

 char * myFunction (char* &text) 
     { 
       char *temp = (char *)malloc(strlen(text)); 
       char *tmp = temp; 
       while(*tmp != '\0') 
       { 
          *tmp = *text++; //im incrementing the text 
          tmp +=1; 

       } 
      return temp; 

     } 

     char *text = "hello"; 
     cout<<myFunction(text)<<endl; 
+0

* TMP + = 1; - > tmp + = 1; – songyuanyao

+0

更好的使用字符串函数,如[strlen](http://linux.die.net/man/3/strlen)(而不是'sizeof(text)',这将不起作用,除非你想要的大小指针本身)和[strcpy](http://linux.die.net/man/3/strcpy)(而不是手动循环)。另外,不要假设[malloc](http://linux.die.net/man/3/malloc)成功,_always_检查它的返回值(这里是'temp')! – Jens

+0

如果'* text ++'返回''\ 0''那么* tmp + = 1;将增加它 – rajenpandit

回答

1

有很多的代码中的问题,我总结他们在下面的评论:

// Making your argument char*& allows you to modify text variable from 
// calling function, I dont think this was your intention. If you just 
// want to pass string to this function change its type to `const char*`. 
// I dont think this return value you really want here, now you have char, but I 
// suppose you want to return string, so it should be `char*` or `const 
// char*` 
char myFunction (char* &text) 
    { 
      // sizeof(text) will return 4bytes, which is size of pointer, 
      // you want strlen(text)+1 here to get length of string + 1 
      // char for zero (end of string) 
      char *temp = (char *)malloc(sizeof(text)); 
      char *tmp = temp; 

      // You should dereference *tmp, but tmp is uninitialized here, 
      // I think you want to use *text here. 
      while(tmp != '\0') 
      { 
         *tmp = *text++; //im incrementing the text 

         // You are incrementing value pointed by tmp, 
         // if you want to increment tmp to next string 
         // element use tmp++; 
         *tmp +=1; 

      } 

      // Here assign zero to last element of text    

     // temp is char* and your return value is char, this is wrong, 
     // you should change return value of myFunction to char*. Also 
     // remember to call free() on returned string once its no 
     // longer needed - otherwise you will introduce memory leaks 
     return temp; 

    } 




    // This should be `const char *text = "hello";` In c++ string 
    // literals are of type `const char*` 
    char *text = "hello"; 
    cout<<myFunction(text)<<endl; 
+0

检查[malloc](http://linux.die.net/man/3/malloc)的返回值。 – Jens

2
while(tmp != '\0') 

while(*tmp != '\0') 

tmp是永远不会字符串的起始地址'\0'

+1

不过,我看不出他们期望在那里找到一个“\ 0”。这和所有其他错误。 – juanchopanza