[英]How many elements does the compiler take from an array which is function argument?
我聽說當使用數組作為 function 參數時,編譯器將其視為實際上不是數組,而是作為指向數組第一個元素的指針。 因此,當詢問 A(int array) 的大小時,它應該返回指針 4 的大小(以字節為單位)。 但我得到8。有什么問題?
我正在使用代碼塊。
int SumOfElemets(int* A, int size){// int* A or int A[] ... it is the same!
int i, sum = 0;
printf("SOE - Size of A = %d, size of A[0] = %d\n", sizeof(A), sizeof(A[0]));
//here it should be 4 and 4 but i am getting 8 and 4
for (i=0;i<size; i++){
sum += A[i]; //A[i] is *(A+i)
}
return sum;
}
int main(){
int A[] = {1,2,3,4,5};
int size = sizeof(A)/sizeof(A[0]); //size of the array
int total = SumOfElemets(A, size);
printf("Sum of elements = %d\n", total);
printf("Main - Size of A = %d, size of A[0] = %d\n", sizeof(A), sizeof(A[0]));
return 0;
}
嗨,我聽說當使用數組作為 function 參數編譯器時,它實際上不是數組,而是指向數組第一個元素的指針。
首先,編譯器將具有數組類型的 function 參數調整為指向數組元素類型的指針。
例如這些 function 聲明
int SumOfElemets(int* A, int size);
int SumOfElemets(int A[], int size);
int SumOfElemets(int A[1], int size);
int SumOfElemets(int A[100], int size);
是等效的並聲明相同的 function。
另一方面,在表達式中使用的 arrays (例如具有罕見異常的參數表達式)被隱式轉換為指向其第一個元素的指針。
所以這些 function 調用
SumOfElemets(A, size);
SumOfElemets(&A[0], size);
SumOfElemets(A + 0, size);
是等價的。
指針的大小被實現定義為int
類型的 object 的大小,盡管通常sizeof( int )
或在您的代碼的情況下sizeof( A[0] )
等於 4。
請注意帶有sizeof
運算符的表達式的類型為size_t
。 所以你需要使用轉換說明符%zu
到 output 表達式的值而不是%d
printf("SOE - Size of A = %zu, size of A[0] = %zu\n", sizeof(A), sizeof(A[0]));
sizeof
運算符產生其操作數的大小(以字節為單位)。
當您調用sizeof(A)
時,這意味着“指針A
的大小是多少?”。
這與sizeof(A[0])
不同,這意味着“數組A
的第一個元素的大小是多少?”。
類型的大小取決於編譯器,並且在具有 64 位地址空間的 C 實現中, pointers
通常是 64 位(八個 8 位字節),而int
通常是 32 位,因此:
sizeof(A)
8 個字節;sizeof(A[0])
4 個字節。(由Eric Postpischil澄清)
查看以下示例:
使用x64 ( 64 位地址空間)編譯器的示例:https://godbolt.org/z/vYcWhvxsE
Output:
Size of pointer to int (x64): 8
Size of integer (x64): 4
使用x86 ( 32 位地址空間)編譯器的示例:https://godbolt.org/z/68PTsM6db
Output:
Size of pointer to int (x86): 4
Size of integer (x86): 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.