user565447
user565447

Reputation: 999

Changes rows of the matrix

I have an array of structs. Actually, it is a 2d-array but an unusual 2d array. I am allocating memory on stack:

#define MAX_VERTICES 5068
struct ARRAY_FIX {
    int ele[MAX_VERTICES];
    int size;
    int first;
};
ARRAY_FIX C[MAX_VERTICES];
 
int main() {
//...
} 

So, I need to replace one row with another one (actually, i need this operation to be performed for sorting rows by some criteria).

Replacing of the rows

How is it possible to perform? As I understand, if I use this code:

С[i] = C[j];

In this code, the operator "=" will copy all array, won't it? I needn't it, I want to change the rows by changing the pointer

How can I do it?

Upvotes: 2

Views: 199

Answers (3)

MOHAMED
MOHAMED

Reputation: 43518

as said before

Possible solution is to change your 2D array to an array of pointers to struct ARRAY_FIX

here after how to do it:

#define MAX_VERTICES 5068
struct ARRAY_FIX {
    int ele[MAX_VERTICES];
    int size;
    int first;
};
ARRAY_FIX *C[MAX_VERTICES];

int main() {
int i;
ARRAY_FIX *p;
//...
for (i=0;i<MAX_VERTICES;++i)
{
    C[i] = malloc (sizeof(ARRAY_FIX ));
    //...
}
//...
p = C[1];
C[1] = C[2];
C[2] = p;
//...
} 

Upvotes: 1

LihO
LihO

Reputation: 42083

In your case, each row is represented by struct ARRAY_FIX object. If you want to be able to work with these rows by using references (changing the order of rows by swapping pointers etc.), your 2D array must be stored in a way that allows you to do that.

Possible solution is to change your 2D array to an array of pointers to struct ARRAY_FIX so that when you call С[i] = C[j]; only the reference (address of your object) is copied, not an object itself.

Also note, that you should worry about the performance and try to make your program faster only when it's really needed. It's much easier to make a correct program fast than it's to make a fast program correct.

Upvotes: 1

ouah
ouah

Reputation: 145829

You can use an array of pointers to struct ARRAY_FIX and just switch the pointers into the array.

I am allocating memory on stack.

An object declared at file scope is usually NOT on the stack.

Upvotes: 2

Related Questions