c++中的数组和函数
Arrays and functions in C++
我正在使用字符数组。我的函数应该返回一个数组。然后我希望将该数组赋值给另一个char array
。
。我有
char somechar[50];
在Class声明中是私有的
我定义了一个get方法:
char getsomechar(){
return somechar;
}
在我的主要功能,我试图:以如下方式访问:
char newchar[]=getsomechar();
返回类型和函数类型不匹配。所以我把第二行改成:
char *getsomechar(){
return somechar;
}
然而,我仍然有initialization with {...} expected for aggregate object
错误。我读了一些页面,看到在c++中不能按值传递数组。我不能使用数组库。如何使用指针/引用?
实际上是在函数中返回指向数组的指针:
return somechar; //this is the starting address of the array
因此,您应该声明一个char*
并为其分配数组的起始地址,如下所示:
char* newchar=getsomechar();
,现在你可以访问这个指针,就像索引数组一样:
for(int i=0;i<ARRAY_SIZE;i++)
{
newchar[i] = value // whatever operation you want to do here
}
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中