选择使用结构数组在C中排序,错误:“需要左值”

试图对一组Structs进行排序。 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); 

和全选择排序function。 有什么我不明白用C =在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 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; } 

您不能通过将一个指针指向另一个来复制structs 。 这样您就不会创建两个副本,而是将两个指针指向同一个地址。 你需要使用memcpy 。 这是错的:

 temp = asciiArt+pos_min; 

相反,使用:

 void * memcpy ( void * destination, const void * source, size_t num );