【发布时间】:2015-04-23 10:42:02
【问题描述】:
我在 argv 中丢失了字符串,我想对其进行排序。我正在使用 strcmp 和 strcpy 进行排序。
如何将 const char** 转换为可在排序函数中使用的 char 数组?
void sort(const char** sl, int n) {
char s[n][20], t[20];
int i, j;
for (i = 1; i < n; i++) {
for (j = 1; j < n; j++) {
if (strcmp(s[j - 1], s[j]) > 0) {
strcpy(t, s[j - 1]);
strcpy(s[j - 1], s[j]);
strcpy(s[j], t);
}
}
}
printf("\nStrings in order are : ");
for (i = 0; i < n; i++)
printf("\n%s", s[i]);
}
int main(int argc, const char** argv)
{
sort(argv+1, argc-1);
printf("Files: %i\n", argc-1);
return 0;
}
【问题讨论】:
-
您有undefined behavior,因为您将
s1中的字符串与未初始化 数组s[j]进行比较。 -
我还没有比较任何东西,因为我不知道如何从 const char** 转换为 char[]...
-
在
sort中你有strcmp(s[j - 1], s[j])这个表达式,当你第一次调用函数s[j]时会被初始化,导致UB。