指向int数组,从另一个方法传递和使用它 [英] Pointer to int array, passing and using it from another method
问题描述
我没有巩固我对C ++数组的学习,并忘记了如何正确地这样做。我已经使用char数组前面,但它不能正常工作为int数组。
我声明一个新的空白数组:
int myIntArray [ 10];
那么这应该是一个空数组,暂时是正确的?
然后我为这个数组指定一个指针:
int * pMyArray = myIntArray
希望正确的。
另一种方法在其他地方:
anotherMethod(pMyArray)
其中我想将此指针分配给一个局部变量(这是我真的不知道的):
anotherMethod(int * pMyArray){
int myLocalArray [];
myLocalArray [0] = * pMyArray;
}
我没有收到任何编译错误,但我不确定这是就在几条战线上。
编辑:
我应该说我在做什么
真的很简单,我只想从另一个方法修改一个局部数组。
所以我有:
方法1会包含:
$ b bint myArray1 [10] = {0};
方法2将传递指向myArray的指针:
$ b b然后一些代码修改数组中的变量myArray。
解决方案
int myIntArray [10];
这是一个未初始化的数组。它不一定包含
0
。int * pMyArray = myIntArray
好的,
pMyArray
myIntArray
中的第一个元素。anotherMethod(int * pMyArray){
int myLocalArray [10];
myLocalArray [0] = * pMyArray;
}
这不会将指针指定为任何东西,由
pMyArray
指向的int
的本地数组,其中,记住,未初始化。我添加了10
,因为在C ++中不能有一个未知大小的数组。
pMyArray
指向,您需要通过引用传递它:anotherMethod (int *& pMyArray)
此外,如果将其分配给自动存储中的某些值将导致未定义的行为,因为该函数退出时该内存不再有效。
I haven't cemented my learning of C++ arrays and have forgotten how to do this properly. I've done it with char array before but its not working as well for int array.
I declare a new blank int array:
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Then I assign a pointer to this array:
int *pMyArray = myIntArray
Hopefully thats correct to there.
Then I pass this to another method elsewhere:
anotherMethod(pMyArray)
where I want to assign this pointer to a local variable (this is where I'm really not sure):
anotherMethod(int *pMyArray){ int myLocalArray[]; myLocalArray[0] = *pMyArray; }
I'm not getting any compilation errors but I'm not sure this is right on a few fronts. Any and all help and advice appreciated with this.
Edit:
I should have said what I am trying to do.
Very simple really, I'd just like to modify a local array from another method.
So I have:
Method 1 would contain:
int myArray1[10] = {0};
Method 2 would be passed the pointer to myArray:
Then some code to modify the variables in the array myArray.
解决方案int myIntArray[10];
This is an uninitialized array. It doesn't necessarily contain
0
's.int *pMyArray = myIntArray
Okay,
pMyArray
points to the first element inmyIntArray
.anotherMethod(int *pMyArray){ int myLocalArray[10]; myLocalArray[0] = *pMyArray; }
This doesn't assign your pointer to anything, it assigns the first value of the local array to the
int
pointed to bypMyArray
, which, remember, was uninitialized. I added the10
there because you can't have an array of unknown size in C++.To modify what
pMyArray
points to, you need to pass it by reference:anotherMethod(int *& pMyArray)
Also, if you assign it to some values in automatic storage, it will result in undefined behavior, as that memory is no longer valid when the function exits.
这篇关于指向int数组,从另一个方法传递和使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!