我试图在 C 中交换二维数组中的 2 个元素,但没有成功。
到目前为止,感谢您的回答,但我已经编辑了这段代码,以便更清楚地了解我在做什么。
typedef struct smystruct { /* stuff... */ } mystruct;
void nswap( mystruct ** a, mystruct ** b )
{
mystruct * tmp = *a;
*a = *b;
*b = tmp;
}
void nqsort( mystruct ** h, int m, int n )
{
double key = 0.0;
int i = 0, j = 0, k = 0;
if( m < n ) {
// choose the pivot point...
k = (m + n) / 2;
nswap( &h[ n ], &h[ k ] );
key = (*h+m)->prob;
i = m + 1;
j = n;
while ( i <= j ) {
while ( (i <= n) && (*h+i)->prob <= key )
i++;
while ( (j >= m) && (*h+j)->prob > key )
j--;
if ( i < j ) {
nswap( &h[i], &h[j] );
}
}
// swap two elements
nswap( &h[m], &h[j] );
// recursively sort the lesser list
nqsort( h, m, j-1 );
nqsort( h, j+1, n );
}
}
int main()
{
mystruct * p = NULL;
// get the number of nodes (m)...
fscanf( in, "%d", &m );
// allocate memory for the node and connectivity matrix arrays...
p = (mystruct*)malloc( sizeof( mystruct ) * m );
// read in the location and associated probabilities!...
for ( ; loop < m ; ++loop ) {
mystruct * tmpnode = p + loop;
tmpnode->str = (char*)malloc( sizeof( char ) * 1024 );
fscanf( in, "%s %lf", (char *)tmpnode->str, &tmpnode->prob );
}
nqsort( &p, 0, m );
}
不用说这是行不通的。我已经搜索了示例,但似乎没有任何效果。建议 n00b 将不胜感激。