简体   繁体   English

将数组分配给其他变量

[英]Assign array to a different variable

Here is a part of my code 这是我的代码的一部分

int river(int a[], int n){
  int sorted[] = a;
}

n being the size of the array n是数组的大小

I have tried a couple of different ways, including 我尝试了几种不同的方法,包括

sorted[n]

but I get problems each time. 但是我每次都会遇到问题。 What I am trying to do is duplicate the array with a changed variable name. 我想做的是用更改后的变量名复制数组。 The array will be exactly the same, just stored in a different variable (because I want to obtain information but not modify the original array). 该数组将完全相同,只是存储在一个不同的变量中(因为我想获取信息但不修改原始数组)。

Is this just not possible because of something to do with dynamically changing the size of the array, or am I just missing the point? 这是否由于与动态更改数组大小有关而无法实现?还是我只是想念这一点?

Thanks! 谢谢!

First of all, arrays are not assignable. 首先,数组不可分配。 You can either copy the contents of one array into another, or get a pointer to the first element of the array. 您可以将一个数组的内容复制到另一个数组中,也可以获取指向数组第一个元素的指针。 For example 例如

int a[42] = {0};
int* b = a;      // now you can access a's elements as b[0], b[1], etc.
int c[42];
memcpy(c, a, 42*sizeof(int)); //copy elements of a into c

Second, you should note that the function signature 二,要注意函数签名

int foo(int a[]);

is another way of saying 是另一种说法

int foo(int* a);

ie it can take any pointer to int, even ones that don't point to arrays. 即,它可以使用任何指向int的指针,甚至不指向数组的指针。

With that in mind, you can see that you easily lose array size information, which is why you need to pass the size as a parameter: 考虑到这一点,您可以看到很容易丢失数组大小信息,这就是为什么需要将大小作为参数传递的原因:

int foo(int a[], size_t n);

int a[42];
foo(a, 42);

Now, inside the function, you can copy the elements of one array into another: 现在,在函数内部,您可以将一个数组的元素复制到另一个数组中:

int foo(int* a, size_t n)
{
  int sorted[n];
  memcpy(sorted, a, n * sizeof(int));
  // use sorted
  ....
  return 0;
}

You need to allocate space for the new copy of array by yourself. 您需要自己为数组的新副本分配空间。

int *sorted = malloc(n * sizeof(int));
memcpy(sorted, a, n * sizeof(int));

Simply try like this... 只需这样尝试...

   for(int i=0;i<n;i++)
     sorted[i]=a[i];

If you want to use dynamic memory allocation malloc , try this 如果要使用动态内存分配malloc ,请尝试以下操作

     int *sorted = malloc(n * sizeof(int));
     memcpy(sorted, a, n * sizeof(int));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM