Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用指针确保函数调用正确_C++_Pointers - Fatal编程技术网

C++ 如何使用指针确保函数调用正确

C++ 如何使用指针确保函数调用正确,c++,pointers,C++,Pointers,当我这样调用时,以下代码将起作用: char arr[] = "foobar"; reverse(arr); 但当我这样调用时,它将不起作用,因为它指向只读部分 char*a = "foobar"; reverse(a); 现在我的问题是,有什么方法可以避免用户这样呼叫 void reverse(char *str) { char * end = str; char tmp; if (str) { while (*end) {

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

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;
     }
  }
void反向(char*str)
{
char*end=str;
char-tmp;
如果(str)
{ 
while(*结束)
{      
++结束;
}
--结束;
while(str
}

是包含以下字符的
字符数组:
f
o
o
b
a
r
\0
。当

char* a = "foobar";
这是错误的<代码>“foobar”
这是一个字符串文本,此语句必须为

 const char* a = "foobar"; // note the const
不能更改字符串文字

这是一个常见的错误——区分指针和数组


不,没有办法阻止用户使用字符串文本调用
reverse
。“用户”对其行为负责


如果
a
被定义为必须的(使用
const
),编译器将告诉“用户”类似
从“const char*”到“char*”的转换无效

否,无法保证传递给函数的指针是有效的。提供有效数据是调用方的感受。你甚至可以这样做

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

这没有多大意义,但是没有办法反向检查这些东西。

使用
std::string
。在任何损坏之前,
std::string
是具有已知大小的连续内存块

你甚至可以使用

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

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