0

当我这样调用时,下面的代码将起作用:

char arr[] = "foobar";
reverse(arr);

但是当我这样调用时它不起作用,因为它指向只读部分

 char*a = "foobar";
 reverse(a);

现在我的问题是,有什么办法可以避免用户这样打电话?

void reverse(char *str)
{
  char * end = str;
  char tmp;
  if (str) 
  { 
     while (*end)
     {      
       ++end;
     }
     --end;
     while (str < end)
     {
        tmp = *str;
        *str++ = *end;
        *end-- = tmp;
     }
  }

}

4

3 回答 3

2
于 2013-04-13T15:43:47.537 回答
0

No, there is no way to guarantee that pointer being passed to function is valid. It is impressibility of caller to provide valid data. You can even do something like this

  int i = 0xABCD;
  reverse((char*) i);

Which doesn't make much sense but there is no way to check for such things in reverse.

于 2013-04-13T15:44:31.283 回答
0

使用std::string. 抛开任何损坏,astd::string是具有已知大小的连续内存块。

你甚至可以使用std::reverse.

除了使用正确的设置外,编译器还会阻止您将字符串文字分配给char*变量。

于 2013-04-13T15:55:18.480 回答