简体   繁体   English

传入和修改函数中的数组

[英]Passing in and modifying an array in a function

I have been looking at other posts and trying to get this working for a bit, but can't seem to manage it. 我一直在寻找其他帖子,并尝试使它正常工作,但似乎无法管理。

Basically I want to pass a "char myArray[10]" though into a function, have the function assign the values and then hand it back. 基本上,我想将“ char myArray [10]”传递给函数,让函数分配值,然后将其交回。 It generally looks like this at the moment: 目前通常看起来像这样:

int MyClass::GetArray(char array[10])
{   
    char p[10];
    ... // a value is assigned to p
    memcpy(&array, &p, sizeof(p)); // Here array ends up being 0x3232323232323232 <Error reading characters of string.>

    return 0;
}

Called with: 致电:

    char array[10];
    myclass.GetArray(array);

So, I assume I need to pass the array through as a reference to the array[10] created before calling the function. 因此,我假设我需要传递该数组作为对调用该函数之前创建的array [10]的引用。 But for that I am unsure how to create a pointer to a fixed array without making it either a general char* pointer or a pointer to an array of chars. 但是为此,我不确定如何创建一个指向固定数组的指针而不使其成为常规char *指针或chars数组的指针。

Secondly is the memcpy error (in the code comments above). 其次是memcpy错误(在上面的代码注释中)。 I'm not sure if that is related or not though. 我不确定这是否相关。

Then thing is that when you pass an array to a function, it decays to a pointer. 那么,当您将数组传递给函数时,它会衰减为指针。 So when you use the address-of operator & on array in the function, you're taking the address of the pointer, meaning you get a pointer to a pointer. 因此,当您在函数中使用地址运算符& array时,您将获取指针的地址,这意味着您将获得一个指向指针的指针。

That, by the way, leads to undefined behavior . 顺便说一下,这导致了不确定的行为

Other than that it's all okay, you don't have to pass the array (or rather, pointer) by reference. 除此之外,还可以,您不必通过引用传递数组(或更确切地说,指针)。 It's just not very... C++-ish. 只是不是很... C ++-ish。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM