c/c++语言开发共享选择使用结构数组在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 ); 

      以上就是c/c++开发分享选择使用结构数组在C中排序,错误:“需要左值”相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/523048.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐