繁体   English   中英

C ++ char数组空循环时的字符

[英]c++ char array null character while loop

我有一个不断增加char的函数,因此它将在ascci代码中显示下一个char,但是我的问题是它永远不会破坏循环

     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;
while(tmp != '\0')

成为

while(*tmp != '\0')

tmp是字符串开头的地址,永远不会是'\\0'

您的代码中有很多问题,我在下面的评论中总结了这些问题:

 // 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM