我编译了下面的c代码,没有发现错误,但是当我运行它时,程序停止并出现此错误:段错误(核心转储)。我正在尝试对任意行中有一个字符串的数组进行选择排序。任何
#include <stdio.h>
#include <string.h>
#define n 50
int main() {
int i, j, pl; /* pl = number of words */
char words[pl][n];
char *temp;
scanf("%d", &pl);
for (i = 0; i < pl; i++); {
scanf("%s", words[i]);
}
/* bla bla
bla bla */
for (i = 0; i < (pl - 1); i++) {
pos = i;
for (j = i + 1; j < pl; j++) {
if (strcmp(words[pos], words[j]) >= 0)
pos = j;
}
if (pos != i) {
strcpy(temp, words[i]);
strcpy(words[i], words[pos]);
strcpy(words[pos], temp);
}
}
最佳答案
for(i=0; i<pl; i++);
注意分号,下面的 block 只会运行一次。所以你的“单词”将无法正确初始化。
关于c - 字符串数组选择排序 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21218798/