我正在使用CodeBlocks 17.12编译并运行此程序。问题在于array[0]
中主函数中返回的arr
已被更改。我不知道为什么,这是因为我只是将数组的值复制到另一个const
数组中。有人可以向我解释为什么返回的array[0]
的值被更改了吗?
#include<iostream>
int *num(int *arr, const int arr2[], int array2[], const int arraySize){
std::cout << "sizeof(array[0]) = " << sizeof(arr) << std::endl;
int arrSize = arraySize / sizeof(arr);
std::cout << "sizeof(arr) = " << arrSize << std::endl;
while(arrSize > 0){
*arr = *arr * *arr;
std::cout << *arr << std::endl;
arr++;
arrSize--;
}
//copy value of arr2 to array2 while '\0' is not encountered
//there is something wrong here which altered the returned array which is in arr
for(int i = 0; (array2[i] = arr2[i]) != '\0' ;i++){
std::cout << "Arr2[" << i << "] = " << arr2[i] << std::endl;
std::cout << "Array2[" << i << "] = " << array2[i] << std::endl;
}
return arr;
}
int main(){
int x = 5;
int array[] {1, 2, 3, 6, 5, '\0'};
int array2[5];
std::cout << "sizeof(array[]) = " << sizeof(array) << std::endl;
for(int r = 0; r < 5; r++){
std::cout << "array[" << r << "] = " << array[r] << std::endl;
}
int arraySize = sizeof(array);
num(array, array, array2, arraySize);
//array[0] = 0, instead of array[0] = 1 why???
for(int y = 0; y < 5; y++){
std::cout << "array[" << y << "] = " << array[y] << std::endl;
}
return 0;
}
结果
Actual result: 0 4 9 36 25
Expected result: 1 4 9 36 25