这是将数组传递给函数的正确方法吗?

问题描述:

这是在一个函数中传递数组的工作程序,但我无法理解在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

因为数组只是内存中的一组连续字节。你是在自问自答。 a [i]相当于*(a + i),所以你不明白什么? – OldProgrammer 2013-04-20 20:36:44

+5

正确答案:不要。而是传递一个向量。 – 2013-04-20 20:47:02

既然你传递一个指针(指向特定的内存地址),你可以把它当作平常甚至里面的功能。指针和数组的关系非常密切,用法很好。

一个[0]和*一个是相同的东西,所以是[1]和*(A + 1)等

“A指针等效于它的第一个元素的地址点为” - 从http://www.cplusplus.com/doc/tutorial/pointers/

+1

这是因为[数组衰减指针](http://stackoverflow.com/questions/1461432/what-is-array-decaying) – 2013-04-20 20:40:23

+3

而且你甚至可以写'i [a]',因为它扩展为'*(我+ a)'增加了一个指针和一个整数;不过,除非在[IOCCC](http://ioccc.org/)参赛作品中,否则不应该这样做。 – 2013-04-20 20:44:12

阵列可以传递这样的,但其他的方法是把该阵列随后空[]的名称:

#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] 
    } 
} 

两种方法传递的地址数组中的第一个数字,所以这两种方法都有效

+1

你说得对,但要理解它是如何工作的,现在需要额外的一步来实现'int a []',在函数参数声明的特例中,意味着'int * a'。这并不能解释任何事情,这只会让问题复杂化。 – hvd 2013-04-20 21:33:14

//我们如何能够与subscipt A [1]来访问数组

a[i]是一回事*(a + i)


因为它是现在,你print工作的确切大小3的数组,因此:

  • 如果数组恰好有3组以上的元素,有些元素不会被打印。
  • 如果碰巧少于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; 
}