c语言 constant错误,C语言学习——错误记录

1. error: empty character constant

直译:空的字符定义。

错误分析:

原因是连用了两个单引号,而中间没有任何字符。一般的,单引号表示字符型常量,单引号中必须有,也只能有一个字符(使用转义符时,转义符所表示的字符当作一个字符看待)。两个单引号之间不加任何内容是不允许的。

案例:

代码第三行,定义char数组,数组中第二个元素,本该是个空格,但是却在两个单引号中漏了空格字符。

#include

void main(){

char c[]={'I','','a','m',' ','a',' ','g','i','r','l','.'};

int i,len=strlen(c);

for(i=0;i

printf("%c",c[i]);

}

printf("\n");

}

2.warning: incompatible implicit declaration of built-in function ‘strlen’

直译:内置函数strlen不兼容的隐式声明

错误分析:c语言中,如果一个函数没有显示地声明就使用,被看作是隐式声明。现在,gcc已经为一些标准函数做了定义,如果隐式声明与gcc的定义不匹配,就会有warning提示。(In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.)

所以,还可能出现这个问题:“我的程序用到了函数strlen,以前在redhat9.0下编译可以通过,为什么在fedora8下面却出现错误?”,可能是gcc不同的编译版本问题。

案例:上面1中的案例

解决方案:头部加引入 #include

如下:

#include

#include

void main(){

char c[]={'I',' ','a','m',' ','a',' ','g','i','r','l','.'};

int i,len=strlen(c);

for(i=0;i

printf("%c",c[i]);

}

printf("\n");

}

3、strlen()函数

strlen() 函数计算的是字符串的实际长度,遇到第一个'\0'结束。如果str的结尾不是'\0',strlen()会继续向后检索,直到遇到'\0',而这些区域的内容是不确定的。

示例:

#include

#include

void main(){

char c[10] = {"china"};

char d[] = {'c','h','i','n','a','\0'};

char e[] = {'c','h','i','n','a'};

char f[] = "china";

printf("lenc=%d\n",strlen(c));

printf("lend=%d\n",strlen(d));

printf("lene=%d\n",strlen(e));

printf("lenf=%d\n",strlen(f));

}

运行结果:

bb8dc8134517d2ebdcf2c978a4539f31.png

我们看到"lene=10"这一行,明显是错误的结果。就是由于数组中没有添加结束符'\0'导致的。而c和f因为使用了双引号,自动识别为字符串,已包含结束符'\0 '.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值