使用结构体,错误的Array选择排序在C:"需要左值..." [英] Selection Sort in C using an Array of Struct, error: "lvalue required..."
问题描述
试图排序结构的数组。结构是TextArt低于
定义 typedef结构//结构保存ASCII艺术
{
焦炭ARTISTNAME [80]; //艺术家的名字
炭asciiArt [20] [80]; //按行实际的ASCII艺术行
INT评级; //艺术评级
} TextArt;
我不认为结构有什么关系这虽然。我得到的编译器错误
错误:左值试图分配一个结构到另一个需要作为分配的左操作数(如下图所示)
TEMP = asciiArt + pos_min;
asciiArt + pos_min = asciiArt + I; //此处错误
asciiArt +我= *温度; //错误也在这里
呼吁功能
选择排序(artPtr,artArrSize);
和全选择排序功能。是否有什么我不理解有关分配使用=在C结构?我认为这是非此即彼我对TextArt阵传球在某种程度上是错误的。请赐教谢谢。
无效选择排序(TextArt * asciiArt,INT大小)
{
// pos_min是短期的分钟的位置
INT pos_min;
TextArt *温度;
INT I = 0;
INT J = 0; 对于(i = 0; I<大小-1;我++)
{
pos_min = I; //设置pos_min数组的当前索引 为(J = I + 1; J<大小; J ++)
{
如果((STRNCMP((asciiArt + I) - > ARTISTNAME,(asciiArt + J) - > ARTISTNAME))小于0)
{
pos_min = j的; // pos_min将跟踪该min是在索引的,当交换发生这是需要
}
} //如果pos_min不再等于I比必须是已发现了一个较小的值,所以一个交换必须发生
如果(pos_min!=ⅰ)
{
的printf(复制...... \\ n);
TEMP = asciiArt + pos_min;
asciiArt + pos_min = asciiArt + I;
asciiArt +我= *温度;
}
}
交换两个结构正确的方法是:
如果(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;
}
这篇关于使用结构体,错误的Array选择排序在C:&QUOT;需要左值...&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!