我想將數組傳遞給C中的函數,並遍歷它。我有這樣的代碼:C:將數組傳遞給函數,並在接收函數中迭代
#include <stdio.h>
int funct(int * a);
int main(int argc, char ** argv){
int a[5] = {0};
int b[5] = {1, 1};
printf("Size of cache: %d\n", sizeof(a));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(a)/sizeof(a[0])));
for(int i = 0; i < (sizeof(a)/sizeof(a[0])); i++){
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");
printf("Size of cache: %d\n", sizeof(b));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(b)/sizeof(b[0])));
for(int i = 0; i < (sizeof(b)/sizeof(b[0])); i++){
printf("for loop\n");
printf("%d\n", b[i]);
}
printf("\n");
funct(a);
funct(b);
return 0;
}
int funct(int * a){
printf("Size of cache: %d\n", sizeof(a));
printf("Numb of elements in a[]: %d\n", (sizeof(a)/sizeof(a[0])));
printf("Array values:\n");
for(int i = 0; i < (sizeof(a)/sizeof(a[0])); i++){
printf("sizeof(a): %d\n",sizeof(a));
printf("sizeof(a[0]): %d\n",sizeof(a[0]));
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");
return 0;
}
結果是:
Size of cache: 20 Array values: Numb of elments in a[]: 5 for loop 0 for loop 0 for loop 0 for loop 0 for loop 0 Size of cache: 20 Array values: Numb of elments in a[]: 5 for loop 1 for loop 1 for loop 0 for loop 0 for loop 0 Size of cache: 4 Numb of elements in a[]: 1 Array values: sizeof(a): 4 sizeof(a[0]): 4 for loop 0 Size of cache: 4 Numb of elements in a[]: 1 Array values: sizeof(a): 4 sizeof(a[0]): 4 for loop 1
請解釋爲什麼我不能在函數內部陣列上迭代 - 我究竟做錯了(我)以及如何正確(ii)。謝謝
[C sizeof a passed array]的可能重複(http://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array) – juanchopanza