在两个函数之间发送数组C++
Sending an array between two functions C++
我正在尝试在C++的两个函数之间发送一个包含 15 个整数的数组。第一个功能允许用户输入出租车 ID,第二个函数允许用户从数组中删除出租车 ID。但是,我在函数之间发送数组时遇到问题。
void startShift ()
{
int array [15]; //array of 15 declared
for (int i = 0; i < 15; i++)
{
cout << "Please enter the taxis ID: ";
cin >> array[i]; //user enters taxi IDs
if (array[i] == 0)
break;
}
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "n";
if (goBack == 0)
update();
}
void endShift ()
{
//need the array to be sent to here
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "n";
if (goBack == 0)
update();
}
任何帮助都是非常有价值的。非常感谢。
由于数组是在堆栈上创建的,因此您只需将指向第一个元素的指针作为 int* 传递
void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}
int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}
由于数组是在堆栈上创建的,因此一旦在其中创建数组的例程退出,它将不再存在。
在这些函数之外声明数组,并通过引用将其传递给它们。
void startShift(int (&shifts)[15]) {
// ...
}
void endShift(int (&shifts)[15]) {
// ...
}
int main() {
int array[15];
startShift(array);
endShift(array);
}
这并不完全是漂亮的语法或所有常见。更可能的编写方法是传递指向数组及其长度的指针。
void startShift(int* shifts, size_t len) {
// work with the pointer
}
int main() {
int array[15];
startShift(array, 15);
}
惯用C++会完全不同,并使用迭代器从容器中抽象出来,但我想这超出了这里的范围。无论如何,示例:
template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
// work with the iterators
}
int main() {
int array[15];
startShift(array, array + 15);
}
您也不会使用原始数组,但std::array
.
在 startShift()
函数中使用本地数组是行不通的。您最好执行以下一项或多项操作:
-
在调用
startShift()
和endShift()
的函数中使用数组,并将数组传递给这些函数,例如:void startShift(int* array) { ... } void endShift(int* array) { ... } int main() { int arrray[15]; // ... startShift(array); // ... endShift(array); // ... }
-
首先不要使用内置数组:改用
std::vector<int>
:该类会自动维护数组的当前大小。您也可以从函数中返回它,尽管您可能仍然最好将对象传递给函数。
void endShift (int* arr)
{
arr[0] = 5;
}
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- 动态分配的数组和静态数组之间的区别
- 删除[i] 数组和删除数组 [i] 之间的区别
- 当数组位于两个循环之间时,您可以调用数组的 void 函数吗?
- 处理数组时make_unique和make_shared之间的差异
- 在两个结构之间共享数组
- C++堆栈中数组之间的间隙
- 类型测试对象的动态数组的这两个声明之间的区别?
- 如何计算大小为 1000 x 1000 的 2D 数组中 2 个元素之间的步幅?C++
- sizeof(空结构)和sizeof(带有空数组的结构)之间的区别?
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- 如何在带有 mbed 的 nucleo f446re 之间通过带有 UARTSerial 类的 USB 发送字节数组?
- 在给定的整数数组中,可以找到在给定位置之间分类数组的整数之和
- 这两个代码之间的差异(为什么我的数组也有额外的空间,即使我限制了它)
- 使用STD :: String和字符数组之间的选择
- 如何在不复制数据的情况下在平面数组和多维数组之间进行转换?
- 在函数之间传递相同的数组
- 如果 strlen 在 char 数组之间遇到空格,它会怎么做