Reverse C-style String? - C++

前端 未结 5 464
陌清茗
陌清茗 2021-01-01 06:10

I want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficie

5条回答
  •  执笔经年
    2021-01-01 06:32

    Nothing really wrong with yours I would stay away from using well know type names as variables like string for example as it makes it confusing for others to read. Just for one more way you can do it.

    void RevBuff(char* Buffer)
    {
    
    int length = strlen(Buffer);
    char * CpBuff = _strdup(Buffer);
    for(int i = length -1, x = 0; i >=0 ; i--, x++)
    {
        Buffer[x] = CpBuff[i];
    }
    free(CpBuff);
    }
    

    However like stated above you almost always want to use a library function over your own code if you can find one(you have no idea how many times I've seen professional programmers writing code that exists in a standard library when it could have easily been discovered with a Google search but I digress.

提交回复
热议问题