Recently wrote a function, the array as its parameters, the length of the array used in this function, the normal length of seeking the way, should not go wrong; but after running findings is not what I want. Then write a test program to verify my guess.
#include <iostream> using namespace std; void Sort(int nSortArray[6]) { int nLen = sizeof(nSortArray) / sizeof(nSortArray[0]); int nTmp = 0; for (int i = 0; i < nLen; i++) { for (int j = i+ 1; j < nLen; j++) { if (nSortArray[i] > nSortArray[j]) { nTmp = nSortArray[i]; nSortArray[i] = nSortArray[j]; nSortArray[j] = nTmp; } } } } int main() { int nArray[6] = { 0, 8, 3, 2, 10, 9 }; cout << "排序前......" << endl; for (int i = 0; i < sizeof(nArray) / sizeof(nArray[0]); i++) { cout << nArray[i] << "," ; } cout << endl; Sort(nArray); cout << "排序后......" << endl; for (int i = 0; i < sizeof(nArray) / sizeof(nArray[0]); i++) { cout << nArray[i] << "," ; } system("pause"); return 0; }
The code is sorted into an array print found, and the results before and after no change, breakpoint debugging find its length only 1; as follows:
That length sizeof (nSortArray) length and sizeof (nSortArray [0]) are equivalent, while sizeof (nSortArray [0]) is the length of the first address of the array, i.e., it corresponds to a pointer to the first array position value; then the results come out naturally, nSortArray as the parameter, just as the use of a pointer that points to the first location of the array. Therefore, the correct wording should be as follows:
#include <iostream> using namespace std; void Sort(int nSortArray[], int nLen) { int nTmp = 0; for (int i = 0; i < nLen; i++) { for (int j = i + 1; j < nLen; j++) { if (nSortArray[i] > nSortArray[j]) { nTmp = nSortArray[i]; nSortArray[i] = nSortArray[j]; nSortArray[j] = nTmp; } } } } int main() { int nArray[6] = { 0, 8, 3, 2, 10, 9 }; cout << "排序前......" << endl; for (int i = 0; i < sizeof(nArray) / sizeof(nArray[0]); i++) { cout << nArray[i] << "," ; } cout << endl; Sort(nArray, sizeof(nArray)/sizeof(nArray[0])); cout << "排序后......" << endl; for (int i = 0; i < sizeof(nArray) / sizeof(nArray[0]); i++) { cout << nArray[i] << "," ; } system("pause"); return 0; }
The code can be seen from the above, in addition to the array as a parameter a pointer degradation, all other cases the normal length of the array is obtained