【问题标题】:Selection Sort in C using an Array of Struct, error: "lvalue required..."使用结构数组在 C 中进行选择排序,错误:“需要左值...”
【发布时间】:2014-06-03 09:17:13
【问题描述】:

尝试对结构数组进行排序。 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;
    }
}

【问题讨论】:

    标签: c arrays sorting struct variable-assignment


    【解决方案1】:

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

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

    【讨论】:

    • 试过这段代码,它完全被忽略了,“正在复制...”甚至不显示。
    • 如果这部分代码从未到达过,那么问题出在哪里?乍一看,排序似乎是正确的,只有 for (j = i + 1 应该更改。
    • 我不确定,但是当我使用 memcpy 时,会打印“正在复制...”,此代码没有输出。循环中除了 printf 没有其他内容,没有输出。
    • 您的代码有错误,启用编译器警告并尝试编译。
    • 知道了....复制/粘贴时有一个杂散的字符弄乱了代码。谢谢~
    【解决方案2】:

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

    temp = asciiArt+pos_min;
    

    改为:

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

    【讨论】:

    • 谢谢。上帝真是头疼:)
    • 如果可以分配临时结构,为什么还要使用 memcpy。它更好更快,更不容易出错。
    • @self 你能给我举个例子吗?
    • 你可以分配结构;你只需要复制整个结构:TextArt temp = asciiArt[min]; asciiArt[min] = asciiArt[i]; asciiArt[i] = temp; 工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2014-03-12
    相关资源
    最近更新 更多