我正在尝试实现strcmp
和strcpy
以按字母顺序重新排列名称,但名称数组初始化出现了问题。
无法如预期在主控台上打印状态数组。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char sort(char [], char []);
int main() {
char strStates[8] = {
'Ontario', 'Quebec', 'Manitoba', 'Alberta',
'British Colombia', 'Nova Scotia', '\0'
};
char strSorted[] = { '\0' };
int x = 0;
printf("\nThe list of states before being sorted in alphabetical order: %s", strStates);
for (x = 0; x < 7; x++) {
printf("\n%s", strStates);
}
sort(strStates[x], strSorted[x]);
printf("\nThe list of states sorted alphabetically are: ");
for (x = 0; x < 4; x++) {
printf("\n%s", strStates[x]);
}
return 0;
}
char sort(char string1[], char string2[]) {
int x, y = 0;
for (x = 0; x < 3; x++) {
for (y = 1; y < 4; y++) {
if (strcmp(string1[x], string1[y]) > 0) {
strcpy(string2[y], string1[x]);
strcpy(string1[x], string1[y]);
strcpy(string[y], string2[y]);
}
}
}
}
2条答案
按热度按时间unhi4e5o1#
You declared a character array of 8 characters
and trying to initialize it with multibyte character constant as for example
'Ontario'
that have implementation defined values.It seems you want to declare an array of string literals. In this case you should write for example
Also it is a bad idea yo use magic numbers like 8
or 7
or 4
This makes the code unclear.
You can determine the size of the declared array as shown above the following way
As a result for example the for loop that outputs elements of the array can look like
The array strSorted declared like
is not used in your program. Remove the declaration.
This call of the function
sort
does not make sense. The argument expressions have the type
char
while the function expects arguments of the typechar *
.The function sort can be declared the following way
and called like
The function definition that implements the bubble sort method can look like
Here is a demonstration program.
The program output is
lsmd5eda2#
除了阵列初始化之外,还有其他问题....
注意:C中的单引号表示
char
。请使用双引号。更改:至
无处不在。
另外,作为数组中最后一个元素的
\0
不是必需的。每个...“”字符串都包含自己的空终止符。数组初始化:数组的大小必须包含可见字符的数量加上一个额外的字节作为空终止符-数组中最长的字符串。变更
至(包括2D数组符号)
或者改为this(避免需要知道数组中最长的字符串)。
对于比较问题,下面是一个简单的示例,说明如何使用
strcmp()
实现的compare函数和qsort()函数进行比较: