且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用结构体,错误的Array选择排序在C:"需要左值..."

更新时间:2023-02-15 20:01:45

交换两个结构正确的方法是:

 如果(pos_min!= 1)
{
    的printf(复制...... \\ n);
    常量TextArt TEMP = asciiArt [pos_min] //等价于:*(asciiArt + pos_min)
    asciiArt [pos_min] = asciiArt [I]
    asciiArt [I] =温度;
}

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