这是在函数中传递数组的工作程序,但是我无法理解在print
函数中只传递了数组的基地址,但我仍然可以访问数组带下标a[i]
。我知道正确的方法是*(a+i)
,但为什么它也适用于下标?
#include <iostream>
#include <conio.h>
void print(int *a);
using namespace std;
int main()
{
int arr[3]={1,2,3};
print(arr);
getch();
return 0;
}
void print(int *a)
{
for(int i=0;i<3;i++)
{
cout<<a[i];//how we are able to access array with subscipt a[i]
}
}
答案 0 :(得分:3)
由于您传递的是指针(指向特定的内存地址),因此即使在函数内部也可以照常处理。指针和数组非常密切相关,使用也很好。
a [0]和* a是相同的,所以是[1]和*(a + 1)等。
“指针相当于它指向的第一个元素的地址” - 来自http://www.cplusplus.com/doc/tutorial/pointers/
答案 1 :(得分:0)
数组可以这样传递,但另一种方法是将数组的名称后跟空[]:
#include <iostream>
#include <conio.h>
void print(int *a);
using namespace std;
int main()
{
int arr[3]={1,2,3};
print(arr);
getch();
return 0;
}
void print(int a[])
{
for(int i=0;i<3;i++)
{
cout<<a[i];//how we are able to access array with subscipt a[i]
}
}
两种方法都传递数组中第一个数字的地址,因此两种方法都有效。
答案 2 :(得分:0)
//我们如何使用subscipt a [i]
访问数组
a[i]
与*(a + i)
相同。
就像现在一样,您的print
仅适用于精确尺寸为3的数组,因此:
当您将数组传递给函数时,数组的大小会被“遗忘”,因此要么显式传递大小以使函数可以重用于所有大小的数组(可重用性毕竟是函数的重点!)。 ..
void print(int const* a, size_t a_size) {
for (size_t i = 0; i < a_size; ++i) // size_t is the appropriate type here, not int.
std::cout << a[i] << std::endl; // Use std::endl to be able to discern where teh current number ends and the next starts!
}
// ...
int arr[3] = {1, 2, 3};
const size_t arr_size = sizeof(arr) / sizeof(arr[0]);
print(arr, arr_size);
...或者以C ++方式进行并使用std::vector
...
void print(const std::vector<int>& a) {
for (const auto& s : a) // The new C++11 "for each" syntax.
std::cout << s << std::endl;
}
// ...
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
print(a);
......甚至让它变得通用......
template <typename T>
void print(const std::vector<T>& a) {
for (const auto& s : a)
std::cout << s << std::endl;
}