尝试对结构进行排序但出现错误或崩溃

trying to sort structures but errors or crashing

我正在编写一个程序,该程序将按员工编号从低到高对输出进行排序。当我尝试在临时变量前面使用结构名称时,它只是说 'unknown type name strPerson'。我不太确定我需要做什么,我只将指针作为参数传递,因为其他值可以从结构中的成员检索,如 if 语句所示。

你的代码有一些问题,

  1. 它可能会崩溃,因为 nCount 从未初始化,所以它是未定义的行为。

    我不知道神奇的 5 是从哪里来的,或者它是否正确,但肯定没有初始化 nCount 是个问题,

    for (nCount = 0; nCount < 5; ++nCount)
    

    应该修复它。

    请注意,我说的是“可能”,因为崩溃是一件棘手的事情。其他地方可能存在其他错误的指针操作,这就是为什么调试器对发现此类问题非常有帮助。

  2. 我建议将元素个数作为参数传递。

  3. 您可能需要 struct strPerson 而不是 strPerson

    虽然在 c++ 语言中你可以直接使用结构名称,但在 c 中你不能,除非你 typedef

    typedef struct strPerson {
        /* The definition in here */
    } strPerson;
    

    那么您的代码将按原样运行。 (当然首先修复 (1)。)

这应该可以修复它:nCount = 0; 在 for 循环中

并在 strPerson

之前添加 struct

此行开头缺少关键字 struct

strPerson temp = ptrPerson[nCount + 1];

应该是

struct strPerson temp = ptrPerson[nCount + 1];

您的代码中存在多个问题:

  • nCount 未初始化。这具有未定义的行为,如果它恰好具有负值,肯定会导致崩溃。
  • type strPerson 似乎未定义,产生编译错误。使用 struct strPerson 或使用 typedef struct strPerson strPerson;.
  • 定义 strPerson
  • 您还忘记在交换后递减索引,导致排序顺序不正确。
  • 数组大小未指定为参数,算法中的值 5 将对应于 6 个元素的数组。

您应该将数组中的元素数量指定为参数,并在您的代码中使用此变体:

void fnEmployeeNumSort(struct strPerson *ptrPerson, size_t count) {
    for (size_t i = 0; i < count - 1; i++) {
        if (ptrPerson[i].nEmployeeNum > ptrPerson[i + 1].nEmployeeNum) {
            struct strPerson temp = ptrPerson[i + 1];
            ptrPerson[i + 1] = ptrPerson[i];
            ptrPerson[i] = temp;
            if (i > 0) {
                i -= 2;
            }
        }
    }
}

When I try and use the struct name in front of the temp variable it just says 'unknown type name strPerson'

没有类型strPerson。有类型struct strPerson。所以编译器为声明

发出错误
strPerson temp = ptrPerson[nCount + 1];

你至少应该写

struct strPerson temp = ptrPerson[nCount + 1];

变量nCount也没有初始化。所以函数有未定义的行为。

不清楚幻数 5 的含义。如果它是传递给函数数组的大小,那么函数再次具有未定义的行为,因为表达式 nCount + 1 可能超出数组的有效索引范围。

函数本身应该这样声明

void fnEmployeeNumSort( struct strPerson *ptrPerson, size_t n );

其中第二个参数n指定排序序列的大小。

最后函数没有进行排序。排序算法实现不正确。

这是一个演示程序,展示了该函数如何实现冒泡排序算法。

#include <stdio.h>

struct strPerson
{
    int nEmployeeNum;
};

void fnEmployeeNumSort( struct strPerson *ptrPerson, size_t n )
{
    for ( size_t last = n; !( n < 2 ); n = last )
    {
        for ( size_t i = last = 1; i < n; i++ )
        {
            if ( ptrPerson[i].nEmployeeNum < ptrPerson[i - 1].nEmployeeNum )
            {
                struct strPerson temp = ptrPerson[i];
                ptrPerson[i] = ptrPerson[i - 1];
                ptrPerson[i - 1] = temp;
                last = i;
            }
        }
    }       
}

#define N   5

int main(void) 
{
    struct strPerson p[N] = { { 5 }, { 4 }, { 3 }, { 2 }, { 1 } };

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", p[i].nEmployeeNum );
    putchar( '\n' );

    fnEmployeeNumSort( p, N );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", p[i].nEmployeeNum );
    putchar( '\n' );

    return 0;
}

程序输出为

5 4 3 2 1 
1 2 3 4 5