[英]Copying one int array to another C++
试图编写一个程序,将值从一个分配的数组转换为另一个未分配的数组。 我写的代码:
#include "stdafx.h";
#include <iostream>;
using namespace std;
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int j[10];
int copy_array(int *p1, int n);
int *p2, *p2;
int main() {
for (int l = 0; l < 10; l++) {
cout << a[l] << endl;
}
copy_array(a, 10);
for (int i = 0; i < 10; i++) {
j[i] = &p2;
cout << j[i] << endl;
}
system("PAUSE");
return 0;
}
int copy_array(int *p1, int n) {
while (n-- > 0) {
*p1 = *p2;
*p1++;
*p2++;
}
}
我正在使用Microsoft Visual Studio平台,但出现的错误是“没有上下文可以进行这种转换”。 为什么我不能使用此int转换路径? 我如何使用int类型转换(如果可能)修复并连接2个数组?
我尝试操作的是本地函数copy_array,以便它使用j [10]数组整数的地址进行转换,但这给了我另一个错误。 任何支持和建议,将不胜感激。
您不需要p2是全局的。
只需将参数添加到copy_array
。
像这样:
void copy_array(int *p1, int *p2, int n) {
while (n-- > 0) {
*p1 = *p2;
p1++;
p2++;
}
}
并这样调用:
copy_array(j, a, 10);
另外:要打印副本,您只需执行以下操作:
for (int i = 0; i < 10; i++) {
cout << j[i] << endl;
}
这些是您的代码上的一些注意事项:
p2
声明: int *p2, *p2;
。 您还需要初始化它。 所以做到: int *p2 = j;
(实际上,您实际上不需要使用此全局变量-您可以根据需要传递j
来实现相同的效果)。 *p2 = *p1;
不是*p1 = *p2;
-右侧分配给左侧。 j
,不需要j[i] = &p2;
这会改变j
的内容。 更正它们,您的代码应该可以正常工作。
但是,您根本不需要指针来执行此操作。
考虑以下代码并将其与您的代码进行比较:
#include <iostream>
using namespace std;
void copy_array(int [], int [], int);
void print_array(int [], int);
int main() {
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int j[10];
print_array(a,10);
copy_array(a, j, 10);
print_array(j,10);
return 0;
}
void copy_array(int s[], int d[], int n) {
for (int i = 0; i < n; i++)
d[i] = s[i];
} // s for source & d for destination
void print_array(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n\n";
}
我想以@Shadi的答案为基础,您应该对此予以支持,并使代码更具C ++特色。
return 0;
从主要 如果您还没有返回任何其他信息,则暗示。 i
和j
是整数标量的通用变量名,例如,计数器-而不是数组。 我建议您使用a
和b
表示数组,或者使用values
和copy_of_values
等。 std::vector
的类似数组的容器类。 它与数组不完全相同; 例如,它使用动态分配的内存,并且大小可以增加或缩小。 您可能要使用它的原因是它允许您执行普通分配,并与它一起使用其他标准库功能。 因此,沙迪的程序变为:
#include <iostream>
#include <vector>
void print_vector(const std::vector<int>& vec);
int main() {
std::vector<int> a { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> b;
print_vector(a);
b = a;
print_vector(b);
}
void print_vector(const std::vector<int>& vec) {
// this next line uses syntax from the 2011 version of
// the C++ language standard ("C++11").
for(int x : vec) {
std:cout << x << " ";
}
cout << "\n\n";
}
std::for_each
或std::for_each_n
完全避免print_vector
的循环,但这将需要一些迭代器和lambda函数的知识,对于初学者来说可能有些高级,所以我不再赘述那。 但更重要的是,你可以定义为一个出流运营商std::vector
的,因为看到这里 ,与您可以写std::cout << a;
并有工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.