c++中的数组和函数

Arrays and functions in C++

本文关键字:函数 数组 c++      更新时间:2023-10-16

我正在使用字符数组。我的函数应该返回一个数组。然后我希望将该数组赋值给另一个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
}