在 cpp 中传递双指针时出现编译错误
Compilation error while passing double pointer in cpp
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
void f(char **x)
{
(*x)++;
**x = 'a';
}
int main()
{
char str[]="hello";
f(&str);
cout << str << endl;
return 0;
}
请告诉我为什么这个程序出现编译错误。我正在使用 g++ 编译器
Error :temp1.cpp:16:8: error: cannot convert ‘char (*)[6]’ to ‘char**’ for
argument ‘1’ to ‘void f(char**)’
数组
可以隐式转换为指针,但这并不意味着隐式的"指针等效"已经存在。
您希望f(&str);
将隐式创建指向str
的指针和指向该指针的指针。
这个小的(有效的)变化说明了这一点:
int main()
{
char str[]="hello";
char *pstr = str; // Now the pointer extists...
f(&pstr); // ...and can have an address
cout << str << endl;
return 0;
}
您正在将常量字符的指针传递给函数,但在函数中,您将其作为指针的指针。这就是问题所在。我在下面评论了问题所在。[题外话,但注意:数组和指针是不同的概念。
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
void f(char **x) //**x is pointer of pointer
{
(*x)++;
**x = 'a';
}
int main()
{
char str[]="hello";
f(&str); //You are passing pointer of constant char.
cout << str << endl;
return 0;
}
你的函数f
会遇到一个严重的问题,因为&str
和&str[0]
都计算到相同的值......正如其他海报所指出的,这些操作指向不同的类型,但实际的指针 R 值将是相同的。 因此,f
当你试图双重取消引用char**
指针x
时,即使你尝试了类似强制转换的东西来调整类型差异并允许编译发生错误,你也会得到一个段错误。 这是因为您永远不会获得指向指针的指针...&str
和 &str[0]
的计算结果为相同的指针值这一事实意味着双反引用会尝试将 str[0]
中的char
值用作指针值,这将不起作用。
您的问题是您将数组视为指针,而实际上并非如此。 数组衰减为指针,在这种情况下,它不会。你传入的是一个char (*)[6]
,当它期望一个char **
。这些显然是不一样的。
将参数更改为char (*x)[6]
(或使用带有大小参数的模板):
template <std::size_t N>
void f(char (*x)[N])
进入后,您尝试增加 x 指向的内容。您无法递增数组,因此请改用实际指针:
char *p = *x;
p++;
*p = 'a';
全部放在一起,(示例)
template <std::size_t N>
void f(char(*x)[N])
{
if (N < 2) //so we don't run out of bounds
return;
char *p = *x;
p++;
*p = 'a';
}
相关文章:
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?