[英]How to copy contents of one array to another using pointers in C?
I have three Pointers: 我有三个指针:
int *x,*y, *Temp;
And then I have done 然后我做了
x = (int *)malloc(sizeof(int)*m);
y = (int *)malloc(sizeof(int)*n);
Temp = (int *)malloc(sizeof(int)*(m+n));
where m and n are certain values. 其中m和n是特定值。
Next, I have entered values into Temp. 接下来,我在“温度”中输入了值。
for(i=0; i < m+n; i++) {
scanf("%d", Temp+i);
}
I want half of Temp in x and the other half in y. 我希望在X中获得一半的Temp,在y中获得另一半。 How do I do this?
我该怎么做呢?
for(i=0; i < m; i++) {
x[i] = Temp[i];
}
The code above to copy the contents is not working! 上面复制内容的代码不起作用!
Also, how do I print the values? 另外,如何打印值?
Using memcpy
is probably the easiest way to accomplish what you want: 使用
memcpy
可能是实现所需目标的最简单方法:
memcpy(x, Temp, m * sizeof*Temp);
memcpy(y, &Temp[m], n * sizeof*Temp);
To print the values, just use printf
: 要打印值,只需使用
printf
:
puts("Values in x:");
for(int i = 0; i < m; ++i) {
printf("%d\n", x[i]);
}
puts("Values in y:");
for(int i = 0; i < n; ++i) {
printf("%d\n", y[i]);
}
Use memcpy
.It will copy desired numbre of bytes . 使用
memcpy
它将复制所需的字节数。
What I was doing is already mentioned in this answer of PC Luddite 在PC Luddite的答案中已经提到了我在做什么
You can use as follows to print the values. 您可以使用以下方法来打印值。 I just use
M
in place of m
for better clarity. 我只是用
M
代替m
以获得更好的清晰度。
for(i=0; i < M; i++) {
printf("VAL: %d\n",x[i]);
}
Similarly you can also print another array y
. 同样,您还可以打印另一个数组
y
。
It doesn't really look like you need to allocate all that memory, nor does it seem like you need to copy it. 看起来好像并不需要分配所有内存,也似乎不需要复制它。 Consider using this alternative approach:
考虑使用这种替代方法:
int* xy = malloc(sizeof(*xy) * (m+n));
int* x = xy;
int* y = xy + n;
...
free(xy);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.