gpt4 book ai didi

c - 使用结构数组在 C 中进行选择排序,错误 : "lvalue required..."

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:03 25 4
gpt4 key购买 nike

尝试对结构数组进行排序。 Struct是下面定义的TextArt

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;

不过我不认为该结构与此有任何关系。我得到编译器错误

错误:当尝试将一个结构分配给另一个结构时,左值需要作为赋值的左操作数(见下文)

temp = asciiArt+pos_min;
asciiArt+pos_min = asciiArt+i; //error here
asciiArt+i = *temp; //error also here

调用函数

selectionSort(artPtr, artArrSize);

和完整的选择排序功能。关于使用 = 在 C 中分配结构,我有什么不理解的地方吗?我认为要么是这个,要么是我传递的 TextArt 数组有某种错误。请赐教,谢谢。

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

最佳答案

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

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

关于c - 使用结构数组在 C 中进行选择排序,错误 : "lvalue required...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com