2016-05-06 77 views
1

当试图在C中编译我的程序时,出于某种原因我试图找出段错误。C在尝试导入头文件并使用它时出现分段错误

这是我的main.c:

#include <stdio.h> 
#include "main.h" 

int main() 
{ 
    printf("My name is %s and is %s\n", NAME, AGE); 
    return 0; 
} 

main.h:

#define AGE 30 
#define NAME "Doelal" 

试图与此编译:

gcc main.c -o main 

当我运行它我得到分段错误

+4

' “我的名字是%s和为%s \ n”' - >'“我的名字是%S并且是%d \ n“' – BLUEPIXY

+0

@BLUEPIXY:OMG ......不过谢谢。 – Doelal

回答

2

原因是您在将AGE宏提供给printf时调用了未定义的行为。代码中的格式字符串需要一个字符串参数,但实际上,您的AGE宏是一个整数常量字面量。

你有2个选择:要么改变格式字符串从

"My name is %s and is %s\n" 

"My name is %s and is %d\n" 

#define AGE 30 

改变您的年龄宏

#define AGE "30" 
2

为了理解正在发生的事情,做手工替换预处理的方式做:

printf("My name is %s and is %s\n", NAME, AGE); 

成为

printf("My name is %s and is %s\n", "Doelal", 30); 

现在在格式字符串参数匹配%符。您是否看到在使用%s格式说明符打印30时出现不匹配?

可以通过提供的年龄正常%d格式说明解决这个问题:

"My name is %s and is %d\n" 
//     ^
相关问题