【问题标题】:(windows) DevC++ GCC compiler hangs up or prints infinite characters(windows) DevC++ GCC 编译器挂起或打印无限字符
【发布时间】:2023-04-09 21:32:01
【问题描述】:

我正在尝试编写一些 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'。为什么会发生这种情况?

【问题讨论】:

  • 你的编译器坏了。获得一个运行良好的新编译器。

标签: c gcc dev-c++


【解决方案1】:
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 是否隐含地将字符视为整数?我在执行“printf(%c, 65)”时看到了这个,它吐出了一个字符。
  • 是的,确实如此。根据N1256 6.2.5 类型,char 是一种标准整数类型
猜你喜欢
  • 1970-01-01
  • 2021-11-23
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
相关资源
最近更新 更多