您的位置:首页 > 编程语言 > C语言/C++

C语言学习——错误记录

2017-02-27 00:00 302 查看

1. error: empty character constant

直译:空的字符定义。

错误分析:

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

案例:

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

#include<stdio.h>
void main(){
char c[]={'I','','a','m',' ','a',' ','g','i','r','l','.'};
int i,len=strlen(c);
for(i=0;i<len;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<string.h>

如下:

#include<stdio.h>
#include<string.h>
void main(){
char c[]={'I',' ','a','m',' ','a',' ','g','i','r','l','.'};
int i,len=strlen(c);
for(i=0;i<len;i++){
printf("%c",c[i]);
}
printf("\n");

}


3、strlen()函数

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

示例:

#include<stdio.h>
#include<string.h>
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));
}

运行结果:



我们看到"lene=10"这一行,明显是错误的结果。就是由于数组中没有添加结束符'\0'导致的。而c和f因为使用了双引号,自动识别为字符串,已包含结束符'\0 '.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言