在 cpp 中传递双指针时出现编译错误

Compilation error while passing double pointer in cpp

本文关键字:编译 错误 指针 cpp      更新时间:2023-10-16
#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';
}