2013-07-28 16 views
3

我想這樣做如下:分配指向數組在C++

int main() { 
    int a[10]; 
    int *d = generateArrayOfSize(10) // This generates an array of size 10 on the heap 
    a = d; 
    print(a); // Prints the first 10 elements of array. 
} 

然而上面的代碼給出編譯錯誤(不兼容的類型中的「詮釋*」分配「INT [10]」)。 我能做些什麼來使上面的代碼工作?

+2

如C++,Bjarne的Stroustrup的,設計者[說](http://www.stroustrup.com/bs_faq2.html#arrays),陣列是「非常低的水平的數據結構,其具有巨大的潛力對於誤用和錯誤,在基本上所有情況下都有更好的選擇「。嘗試使用STL容器。 –

回答

0

因爲數組名稱是不可修改的。所以,你不能做

a = d; 

聲明爲這樣的指針:

int *a; 
2

數組是指針(儘管數組的名字經常衰變到一個指向其第一個元素)。

爲了使上述代碼正常工作,您可以聲明a作爲指針:int *a;。無論如何,print函數需要一個int*(或一個腐爛的數組)。

如果你真的想擁有兩個數組並將內容從一個數組複製到另一個數組,你應該將數據複製到一個循環中。

0

用我的C++生鏽,但嘗試這樣的事情。

int main() { 
    int *a; 
    int *d = generateArrayOfSize(10) // This generates an array of size 10 on the heap 
    a = d; 
    print(a); // Prints the first 10 elements of array. 
} 
2

數組不是指針。

你不能做:

int a[10]; 
int *d; 
a = d; 

將其更改爲:數組和指針之間的C編程

int *a; 
int *d; 
a = d; 

主要區別:

Pointer         | Array 
-------------------------------------------|------------------------------------------- 
A pointer is a place in memory that keeps | An array is a single, pre allocated chunk 
address of another place inside   | of contiguous elements (all of the same 
              | type), fixed in size and location. 
-------------------------------------------|------------------------------------------- 
A pointer can point to a dynamically  | They are static in nature. Once memory is 
allocated memory. In this case, the memory | allocated , it cannot be resized or freed 
allocation can be resized or freed later. | dynamically. 
-------------------------------------------|------------------------------------------- 

你有一個相當這裏有很好的解釋:https://stackoverflow.com/a/7725410/1394283

+2

我實際上找到的差異列表比混亂更有用。 *指針無法在定義時初始化。* =>當然可以:'int a = 3; int * b =&a;',*內存分配可以調整大小或稍後釋放* =>不是指針的特徵,而是* some *指向的內存。 *指針的彙編代碼不同於數組* =>這對初學者來說並不意味着什麼。 –

+0

同意。 '指針無法在定義時初始化.'單獨下調。 – 7stud

+0

@MatthieuM。我刪除了不清楚的部分。但我的意思是指針指向的內存不能在指針定義期間初始化... –

4

數組不可分配且不可複製,因此您必須手動複製每個元素(循環)或使用std::copy

5

如果您使用的是C++,那麼使用C++數組而不是C風格的數組和指針。這裏有一個例子

#include <array> 
#include <iostream> 

template<size_t N> 
std::array<int, N> generateArrayOfSize(void) 
{ 
    std::array<int, N> a; 
    for (int n=0; n<N; ++n) 
     a[n] = n; 
    return a; 
} 

template<size_t N> 
void print(std::array<int, N> const &a) 
{ 
    for (auto num : a) 
     std::cout << num << " "; 
} 

int main() { 
    std::array<int, 10> a; 
    std::array<int, 10> d = generateArrayOfSize<10>(); 
    a = d; 
    print(a); // Prints the first 10 elements of array. 
} 

其輸出0 1 2 3 4 5 6 7 8 9

1

這會以這種方式打印,當您分配一個字符串引用您必須使用* PTR,以你的情況否則打印指針的值的指針打印(d)這就像cout <在C++中它只會打印d [0]的位置。

int ary[5]={1,2,3,4,5}; 
int *d; 
d=ary; 
for(int i=0;i<5;i++) 
cout<<*(d+i);