我正在尝试编写一些 C 代码,在运行以下代码时,我的编译器在打印“A”后突然终止。为什么?
//report expected thing
void Expected(char *s){
int i=0;
int n = sizeof(s)/sizeof(s[0]);
while (i< n)
printf ("%c", s[i]);
printf(" expected.\n");
}
int main(int argc, char *argv){
printf("%c",65); //after this compiler hangs and asks for exit abnormally
char *Arr ={'a'};
Expected(Arr);
return 0;
}
另外,如果我放
char *Arr ={"a"}; //note the double quotes
然后它开始打印出无限数量的“a”。为什么会发生这种情况?
最佳答案
int n = sizeof(s)/sizeof(s[0]);
不是如何获取作为参数传递的指针指向第一个元素的数组的长度。
如果您想让您的函数知道,请传递数组的大小。
char *Arr ={'a'};
这不好,因为 'a'
是一个整数,而您将其转换为指针,那么结果成为有效指针的机会太小。
char *Arr ={"a"};
可以,因为它是一个有效的指针,但是它将是无限循环,因为i
在while
循环中没有更新。
main()
函数的类型是实现定义的。您应该使用标准类型,除非您有某种原因使用特殊的 main()
。
你的代码应该是这样的:
#include <stdio.h>
//report expected thing
void Expected(const char *s, size_t n){ /* add const because the contents of array won't be modified */
size_t i=0; /* use size_t to match type of n */
while (i < n)
printf ("%c", s[i++]); /* update i */
printf(" expected.\n");
}
int main(void){ /* use standard main(). int main(int argc, char **argv) is the another standard type */
printf("%c",65); //after this compiler hangs and asks for exit abnormally
char Arr[] ={'a'}; /* declare an array instead of a pointer */
Expected(Arr, sizeof(Arr)/sizeof(Arr[0]));
return 0;
}
最后,如果崩溃的确实不是您生成的可执行文件,而是您的编译器,请扔掉损坏的编译器,换一个新的。
关于c - (windows) DevC++ GCC 编译器挂起或打印无限字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025693/