我正在尝试为C编程主题完成大学任务.
我已经在我的MacBook上完成了我的任务,我的代码完全符合预期.但是,我们的讲师告诉我们,所有代码都将使用大学Solaris 10 Server进行编译,并且我们被告知如果您的代码无法编译并在其上运行,则会扣除标记.
我们还被告知我们的应用程序将使用以下语法通过标记进行编译:
gcc -ansi -Wall -pedantic assign1.c -lm -o assign1
Run Code Online (Sandbox Code Playgroud)
并执行使用:
./assign1
Run Code Online (Sandbox Code Playgroud)
我的代码目前编译时没有错误或警告并正确执行.但是,我的某个功能在此Solaris机器上无法正常工作.该函数应该是我们自己的基本字符串排序实现 - 用户输入最多40个字符的字符串,它应该转换为小写并按字母顺序排序,并删除所有非字母字符.
在我的Mac上,它输出:
Enter a string (1-40 characters): asdfghjkl
Output: adfghjkls
Run Code Online (Sandbox Code Playgroud)
在学院的Solaris盒子上,它输出:
Enter a string (1-40 characters): asdfghjkl
Output: aa#?dfghjkls
Run Code Online (Sandbox Code Playgroud)
我(大部分)输出的功能是:
void sortLine(int *optionStats, char* source)
{
char tempsort[MAX_SORT_LENGTH + 1];
char comp_c;
int i,j,k;
char c = source[i++];
i = j = k = 0;
optionStats[2]++;
while (c != '\n' && c != '\0' && c != EOF) {
/* convert uppercase characters to lowercase */
if ((int)c >= (int)'A' && (int)c <= (int)'Z')
c = c + ((int)'a' - (int)'A');
/* if the character is alphabeic then sort it else skip it */
if ((int)c <= (int)'z' && (int)c >= (int)'a') {
for (j = 0; j <= MAX_SORT_LENGTH + 1; j++) {
comp_c = tempsort[j];
if (comp_c == '\n' || comp_c == '\0' || comp_c == EOF) {
tempsort[j] = c;
break;
}
if ((int)c <= (int)comp_c) {
for (k = MAX_SORT_LENGTH + 1; k > j; k--) {
tempsort[k] = tempsort[k - 1];
}
tempsort[j] = c;
break;
}
}
}
c = source[i++];
}
/* copy the sorted temporary array into the source array */
for (i = 0; i <= MAX_SORT_LENGTH + 1; i++) {
source[i] = tempsort[i];
}
}
Run Code Online (Sandbox Code Playgroud)
然而,有几个笔记:
函数定义本身(签名)由讲师提供,因此名称,返回类型,参数等不能更改.我们必须按原样使用它(但我们可以在其中做任何我们想做的事情).
代码必须符合ANSI/C90(grr!)
任何人都可以帮助我发现什么导致这些奇怪的额外角色被吐出这个功能 - 它正在我的脑袋?
int i,j,k;
char c = source[i++];
i = j = k = 0;
Run Code Online (Sandbox Code Playgroud)
您在i为其分配值之前使用.您不能假设自动变量将初始化为0.
while (c != '\n' && c != '\0' && c != EOF) {
Run Code Online (Sandbox Code Playgroud)
因为c是char,它不可能相等EOF.不相关,但总有一天你会看到这个bug :)你必须使用一个int这个成语:
int c;
while((c=getchar()) != EOF) {
/* process c */
}
Run Code Online (Sandbox Code Playgroud)
您在tempsort[]初始化之前使用的是:
comp_c = tempsort[j];
Run Code Online (Sandbox Code Playgroud)
您正在将大量数据写回source[]数组:
for (i = 0; i <= MAX_SORT_LENGTH + 1; i++) {
source[i] = tempsort[i];
}
Run Code Online (Sandbox Code Playgroud)
我希望source[]数组保证足够大以容纳MAX_SORT_LENGTH数据,而不是仅仅足够大以容纳标准C字符串.因为这可能是一位友好的教授,所以可能很好,但这不是我会轻描淡写的假设.
作为最后的暗示,这些(int)演员中的每一个都是无用的; 编译器知道如何比较和对char变量进行算术运算.:)