编译器不显示任何错误或警告,但程序不工作
Compiler doesn't show any errors or warnings but the program doesn't work
我尝试构建并 运行 以下程序,但它无法执行。我以为我可能犯了一个错误,但显示了 0 个错误和 0 个警告。
在研究了 Whosebug 上的此类行为后,我主要看到一些放错地方的分号或忘记的地址运算符,我在这个源代码中没有看到,或者我忽略了什么?
一些 C 或 GCC 大师可以告诉我哪里出了问题以及为什么吗?
操作系统是Windows7,并且编译器已经启用:
-pedantic -w -Wextra -Wall -ansi
这里是源代码:
#include <stdio.h>
#include <string.h>
char *split(char * wort, char c)
{
int i = 0;
while (wort[i] != c && wort[i] != '[=10=]') {
++i;
}
if (wort[i] == c) {
wort[i] = '[=10=]';
return &wort[i+1];
} else {
return NULL;
}
}
int main()
{
char *in = "Some text here";
char *rest;
rest = split(in,' ');
if (rest == NULL) {
printf("\nString could not be devided!");
return 1;
}
printf("\nErster Teil: ");
puts(in);
printf("\nRest: ");
puts(rest);
return 0;
}
预期的行为是字符串 "Some text here" 在其第一个 space ' ' 处被拆分,预期的输出将是:
Erster Teil: Some
Rest: text here
您正在修改字符串文字,这是未定义的行为。改变这个
char* in = "Some text here";
到
char in[] = "Some text here";
这使 in
成为一个数组并用 "Some text here"
初始化它。您应该使用 const
来防止在定义指向字符串文字的指针时意外出现此错误。
我尝试构建并 运行 以下程序,但它无法执行。我以为我可能犯了一个错误,但显示了 0 个错误和 0 个警告。
在研究了 Whosebug 上的此类行为后,我主要看到一些放错地方的分号或忘记的地址运算符,我在这个源代码中没有看到,或者我忽略了什么? 一些 C 或 GCC 大师可以告诉我哪里出了问题以及为什么吗?
操作系统是Windows7,并且编译器已经启用: -pedantic -w -Wextra -Wall -ansi
这里是源代码:
#include <stdio.h>
#include <string.h>
char *split(char * wort, char c)
{
int i = 0;
while (wort[i] != c && wort[i] != '[=10=]') {
++i;
}
if (wort[i] == c) {
wort[i] = '[=10=]';
return &wort[i+1];
} else {
return NULL;
}
}
int main()
{
char *in = "Some text here";
char *rest;
rest = split(in,' ');
if (rest == NULL) {
printf("\nString could not be devided!");
return 1;
}
printf("\nErster Teil: ");
puts(in);
printf("\nRest: ");
puts(rest);
return 0;
}
预期的行为是字符串 "Some text here" 在其第一个 space ' ' 处被拆分,预期的输出将是:
Erster Teil: Some
Rest: text here
您正在修改字符串文字,这是未定义的行为。改变这个
char* in = "Some text here";
到
char in[] = "Some text here";
这使 in
成为一个数组并用 "Some text here"
初始化它。您应该使用 const
来防止在定义指向字符串文字的指针时意外出现此错误。