#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;
}
请告诉我为什么这个程序正在编译Error.I我正在使用g ++编译器
Error :temp1.cpp:16:8: error: cannot convert ‘char (*)[6]’ to ‘char**’ for
argument ‘1’ to ‘void f(char**)’
答案 0 :(得分:3)
数组可以隐式转换为指针,但并不意味着隐含的“指针等效”已经存在。
您希望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;
}
答案 1 :(得分:0)
您正在将常量char的指针传递给函数,但在函数中,您将其作为指针的指针。那就是问题所在。我在下面评论了问题所在。 [关闭主题,但是N. B.:数组和指针是不同的概念。]
#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;
}
答案 2 :(得分:0)
你的功能f
会遇到严重问题,因为&str
和&str[0]
都会评估相同的价值......正如其他海报所指出的那样操作指向不同的类型,但实际指针r值将是相同的。因此,在f
中,当您尝试对char**
指针x
进行双重取消引用时,即使您尝试使用强制转换来按摩类型差异并允许,也会出现段错误编译发生错误。这是因为你永远不会得到一个指向指针的指针... &str
和&str[0]
计算相同指针值这一事实意味着双解引用实际上试图使用{{1 char
中的值作为指针值,不起作用。
答案 3 :(得分:0)
你的问题在于你将数组视为指针,当它们不是时。数组衰减成指针,在这种情况下,它没有。当您期望char (*)[6]
时,您传入的内容为char **
。那些显然是不一样的。
将参数更改为char (*x)[6]
(或使用带有尺寸参数的模板):
template <std::size_t N>
void f(char (*x)[N])
进入内部后,您尝试增加x指向的内容。您不能递增数组,因此请改用实际指针:
char *p = *x;
p++;
*p = 'a';
全部放在一起,(sample)
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';
}