提问人:Roshan R. Prasad 提问时间:11/18/2023 更新时间:11/18/2023 访问量:56
我想知道当我们可以使用第二个代码 [duplicate] 获得相同的结果时,在第一个代码中使用指针有什么意义
I want to know what is the point of using pointer in first code when we can get same result using second code [duplicate]
问:
第一个包含指针的代码文件:*ptr
#include <iostream>
int main(){
int size;
int *ptr;
std::cout << "Enter number of values you want to store (size of array): ";
std::cin >> size;
ptr = new int[size];
std::cout << "Enter values to be stored in the array: " << std::endl;
for(int i=0; i<size; i++){
std::cin >> ptr[i];
}
std::cout << "Values in the array are: " << std::endl;
for(int i=0; i<size; i++){
i == 0 ? std::cout << ptr[i] : std::cout << " " << ptr[i] ;
}
delete[] ptr; //Freeing the dynamically allocated memeory(in order to avoid memory leak)
return 0;
}
第二个代码文件不包含任何指针,但仍给出相同的结果:
#include <iostream>
int main(){
int size;
std::cout << "Enter number of values you want to store(size of the array): ";
std::cin >> size;
int theArray[size];
std::cout << "Enter values to be stored in the array: " << std::endl;
for(int i=0; i<size; i++){
std::cin >> theArray[i];
}
std::cout << "Values in the array are : " << std::endl;
for(int i=0; i<size; i++){
i == 0 ? std::cout << theArray[i] : std::cout << " " << theArray[i];
}
return 0;
}
我只是想知道为什么每个人都建议我使用第一个代码而不是第二个代码。
请向我解释一下。
答: 暂无答案
评论