[英]Arrays and functions in C++
I am working with array of chars. 我正在处理各种字符。 My function is expected to return an array.
我的函数应该返回一个数组。 Then I expect to assign that array to a different
char array
. 然后我希望将该数组分配给不同的
char array
。
eg I have 我有
char somechar[50];
in Class declaration, it is private. 在类声明中,它是私有的。
I defined a get method as : 我将get方法定义为:
char getsomechar(){
return somechar;
}
in my main function, I am trying to: access it assign as: 在我的主要功能中,我试图:访问它分配为:
char newchar[]=getsomechar();
I was given return type and function type do not match. 我被赋予了返回类型和函数类型不匹配。 So I corrected second line to:
所以我纠正了第二行:
char *getsomechar(){
return somechar;
}
However I am still having initialization with {...} expected for aggregate object
error. 但是我仍然在
initialization with {...} expected for aggregate object
错误。 I read some pages and saw that you cannot pass array by value in C++. 我读了一些页面,发现你不能在C ++中按值传递数组。 I can't use array library.
我不能使用数组库。 How do I do it with pointers/references?
如何使用指针/引用进行操作?
You are essentially returing a pointer to the array in your funciton: 你基本上是在你的函数中引导一个指向数组的指针:
return somechar; //this is the starting address of the array
So, you should declare a char*
and assign the starting address of the array to it, like so : 因此,您应该声明一个
char*
并将数组的起始地址分配给它,如下所示:
char* newchar=getsomechar();
and now you can access this pointer, like an array by indexing: 现在你可以通过索引来访问这个指针,就像一个数组:
for(int i=0;i<ARRAY_SIZE;i++)
{
newchar[i] = value // whatever operation you want to do here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.