A correct way to swap the two structs would be:
if (pos_min != i)
{
printf("copying...\n");
const TextArt temp = asciiArt[pos_min]; //equivalent to: *(asciiArt + pos_min)
asciiArt[pos_min] = asciiArt[i];
asciiArt[i] = temp;
}
Вопрос
Trying to sort an array of Structs. Struct is TextArt defined below
typedef struct //struct that holds ASCII art
{
char artistName[80]; //name of artist
char asciiArt[20][80]; //actual ascii art line by line
int rating; //rating of art
}TextArt;
I don't think the struct has anything to do with this though. I get the compiler error
error: lvalue required as left operand of assignment when trying to assign one struct to another(seen below)
temp = asciiArt+pos_min;
asciiArt+pos_min = asciiArt+i; //error here
asciiArt+i = *temp; //error also here
Call to function
selectionSort(artPtr, artArrSize);
and full selection sort function. Is there something I'm not understanding about assigning structs in C using =? I thought it was either this or my passing of the TextArt array was somehow wrong. Please enlighten me and thank you.
void selectionSort(TextArt *asciiArt, int size)
{
//pos_min is short for position of min
int pos_min;
TextArt *temp;
int i=0;
int j=0;
for (i=0; i < size-1; i++)
{
pos_min = i;//set pos_min to the current index of array
for (j = i + 1; j < size; j++)
{
if ((strncmp((asciiArt+i)->artistName, (asciiArt+j)->artistName)) < 0)
{
pos_min = j; //pos_min will keep track of the index that min is in, this is needed when a swap happens
}
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
printf("copying...\n");
temp = asciiArt+pos_min;
asciiArt+pos_min = asciiArt+i;
asciiArt+i = *temp;
}
}
Решение
A correct way to swap the two structs would be:
if (pos_min != i)
{
printf("copying...\n");
const TextArt temp = asciiArt[pos_min]; //equivalent to: *(asciiArt + pos_min)
asciiArt[pos_min] = asciiArt[i];
asciiArt[i] = temp;
}
Другие советы
You cannot copy structs
by assigning one pointer to the other. This way you are not creating two copies instead you are pointing both the pointers to the same address. You need to use memcpy
instead. This is wrong:
temp = asciiArt+pos_min;
instead, use:
void * memcpy ( void * destination, const void * source, size_t num );