简体   繁体   English

简单的 Hello World 示例中的分段错误?

[英]Segmentation Fault on simple Hello World example?

I'm just starting out with C and I've got this code block for beginners:我刚开始使用 C,我为初学者准备了这个代码块:

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf('     /\n');
    printf('    /\n');
    printf('   /\n');
    printf('  /\n');
    printf(' /\n');
    printf('/\n');
    return 0;
}

I'm using Code Blocks to build and run it.我正在使用代码块来构建和运行它。 It prints out Segmentation Fault, core dumped .它打印出Segmentation Fault, core dumped The editor is using default gcc compiler.编辑器使用默认的 gcc 编译器。

What's wrong with the code?代码有什么问题?

You use single quotes calling printf instead of double quotes.您使用单引号调用printf而不是双引号。 It's going to turn the first few characters into an integer, and cast that integer as a pointer and access wherever it points as a format string, which is most likely not yet mapped, so segmentation fault.它将前几个字符转换为 integer,并将该 integer 转换为指针并访问它指向的任何地方作为格式字符串,这很可能尚未映射,因此分段错误。

Use double quotes.使用双引号。

As Ed Heal mentioned, always compile with warnings enabled.正如 Ed Heal 提到的,始终在启用警告的情况下进行编译。 C isn't like other languages. C 与其他语言不同。 Warnings are usually very serious problems.警告通常是非常严重的问题。

Use double quotes for strings:对字符串使用双引号:

int main() {
    printf("     /\n");
    printf("    /\n");
    printf("   /\n");
    printf("  /\n");
    printf(" /\n");
    printf("/\n");
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM