简体   繁体   English

如何使用C中的指针将一个数组的内容复制到另一个数组?

[英]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]);
}

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.

相关问题 C - 使用指针将一个char数组的内容复制到另一个char数组 - C - Copy contents of one char array to another using pointers 如何使用指针将一个变量的内容复制到另一个变量? - How can i copy the contents of one variable to another using pointers? 如何使用指针将字符数组复制到&#39;c&#39;中的另一个字符数组中,而不使用字符串库 - How to copy a character array into another character array in 'c' using pointers and without using string library 在指向结构的指针中将一个数组的内容复制到另一个数组中 | C - Copy the contents of one array into another within a pointer to a structure | C c指针和数组,将内容复制到另一个数组中 - c pointers and arrays, copying contents into another array 如何在C中逐字将内容从一个文件复制到另一个文件? - How to copy contents from one file to another word by word in C? 如何在C中将一个数组的数据复制到另一个数组? - How to copy data of one array to another in C? 如何在 C 编程中将一个数组复制到另一个数组 - How to copy one array to another in C programming 如何使用Xlib将一个窗口的内容复制到另一个窗口? - How can I copy contents of one window to another using Xlib? 如何将结构内容复制到另一个结构中,包括指针 - How to copy structure contents into another structure including pointers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM