Dog
Dog

Reputation: 605

Swapping an array of structs' element with another element

I'm trying to swap an array of structs, and I thought following a similar fashion of storing in a temp would work like this:

int temp ,a, b;
temp = a;
a = b;
b = temp;

My array of struct definition is this:

struct storage data[10];

My attempt to swap an array of structs, I tried this:

struct storage temp[1];
temp = data[1];
data[1] = data[2];
data[2] = temp;

Unfortunately, it doesn't compile

My errors are below:

error #2168: Operands of '=' have incompatible types 'struct storage[1]' and 'struct storage'.

error #2088: Lvalue required.

error #2168: Operands of '=' have incompatible types 'struct storage' and 'struct storage*'.

Upvotes: 1

Views: 1177

Answers (2)

Kobo
Kobo

Reputation: 11

You are trying to hold a struct storage that you dereferenced when you said

temp = data[1];

You need to declare your temp variable as such to hold the dereferenced values from the array

struct storage temp;

Upvotes: 1

cnicutar
cnicutar

Reputation: 182639

In C arrays aren't modifiable lvalues. Drop the [1] and you're set:

struct storage temp;

Upvotes: 5

Related Questions