mrybak834
mrybak834

Reputation: 147

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!

Upvotes: 0

Views: 376

Answers (3)

juanchopanza
juanchopanza

Reputation: 227410

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);

i.e. 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;
}

Upvotes: 4

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

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));

Upvotes: 1

timrau
timrau

Reputation: 23058

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));

Upvotes: 1

Related Questions