简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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