2017-03-21 38 views
-2

我想創建一個包含8個其他數組的數組。我有一個函數將這些數組放在一個更大的數組中。我無法引用在子陣我的數據:引用數組指針的值

void randomGen(int arr[]){ 
// fill vec10-vec1000000 with random values 
arr[0] = *vec10; 
arr[1] = *vec100; 
arr[2] = *vec1000; 
arr[3] = *vec10000; 
arr[4] = *vec100000; 
arr[5] = *vec100000; 
arr[6] = *up; 
arr[7] = *down; 
} 

我在主要測試這一點,我不能找到一種方法來訪問任何東西,但每個陣列中的第一個值。我不確定第一列顯示的是什麼,第二列是每個vec10-vec1000000中的第一個條目,第三列僅僅是在第一個條目上迭代+1。我如何格式化,以便我可以訪問我的子數組?我的功能註定了嗎?

First 4 elements of vec10: 12 5 9 17 
0: *(*(&a+i)): 12; *(a+i): 12; *(a)+i: 12 
1: *(*(&a+i)): 0; *(a+i): 1144108930; *(a)+i: 13 
2: *(*(&a+i)): 0; *(a+i): 984943658; *(a)+i: 14 
3: *(*(&a+i)): 0; *(a+i): 1622650073; *(a)+i: 15 
4: *(*(&a+i)): 0; *(a+i): 282475249; *(a)+i: 16 
5: *(*(&a+i)): 0; *(a+i): 282475249; *(a)+i: 17 
6: *(*(&a+i)): 0; *(a+i): 0; *(a)+i: 18 
7: *(*(&a+i)): 0; *(a+i): 9999; *(a)+i: 19 
8: *(*(&a+i)): 0; *(a+i): 0; *(a)+i: 20 
9: *(*(&a+i)): 0; *(a+i): 0; *(a)+i: 21 
+0

** vec10-vec100000,up **和** down **是int數組嗎?他們來自哪裏?如果是這種情況,你的** arr **參數應該是函數簽名中的一個二維數組:'void randomGen(int ** arr)',然後你可以使用arr [i] [j]來訪問它的值,其中**我**和** j **代表您的行和正在訪問的列。 – 0xDEFACED

+0

是的,這些向量是int數組。我嘗試了你的建議@聖地亞哥瓦雷拉,我得到一個不良訪問錯誤。我做了以下調整:'int ** a;'在randomGen函數中聲明爲main,'void randomGen(int ** arr){'和'arr [0] = vec10;',並且for(int i = 0; i <10; i ++){cout <

回答

-1

以下代碼片段可以幫助我們瞭解關於指針和數組的所有內容。

// say you have 
int a[10], b[10], c[10]; 
// you can 
int *p[3] = {a, b, c}; // implicit conversion from int[10] to int * 
// or 
int (*pa[3])[10] = {&a, &b, &c}; 
// which is equivalent to 
using Array10 = int[10]; 
using PointerToArray10 = Array10 *; 
PointerToArray10 another_pa[3] = {&a, &b, &c}; 

// say you have 
int d[10], e[11], f[12]; 
// you can still 
int *pp[3] = {d, e, f}; 

// say you have 
void randomGen(int arr[]) 
// there isn't anything you can do 

你需要的是

void randomGen(int *arr[]) { 
    arr[0] = a; // no deference, the same a as declared before 
    arr[1] = f; 
} 

由於這些陣列WHI你要「存儲」在arr有不同的類型(綁定),唯一的選擇是存儲每個數組的第一個元素的地址,即& a [0]。 Arr因此需要有an array of pointers這個類型(這個數組的每個元素都是一個指針)。

但是無法將數組聲明爲函數參數,它們將始終衰減爲指針。因此,這裏的交易,你聲明指針數組的地方:

int *array[10]; 

,然後將它傳遞給函數

randomGen(array); 

和功能使用您傳遞給指針初始化到指針數組,即int **arrint *arr[](它們在參數列表中相同),並進行數組到指針的轉換。而功能參數實際上將指向array的第一個元素,即&array[0]。 (array[0]有類型int *,&array[0]有類型int **

函數內部可以通過指針訪問原始數組的元素。

arr[0] // array[0]