c - (windows) DevC++ GCC 编译器挂起或打印无限字符

标签 c gcc dev-c++

我正在尝试编写一些 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"};

可以,因为它是一个有效的指针,但是它将是无限循环,因为iwhile循环中没有更新。

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/

相关文章:

c - gets() 不读取用户输入

c - 如何打印带父节点的层序二叉搜索树

c++ - GCC 中的元组模板

c++ - 在不破坏任何东西的情况下使用 OSX 和 Eclipse 获得一个可用的 C++11 工具链

c - 格式说明符不起作用,给出运行时错误

c++ - 为什么 boost.geometry.index.rtree 比 superliminal.RTree 慢

c - 确保数组在编译时填充到大小

c - 释放内存/跨平台兼容性问题

c - 可执行文件的文本输出部分显示在控制台上

c++ - 在 C++ 中制作基于文本的 RPG 游戏/模板的问题