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

C语言字符指针和字符数组

2014-03-29 15:55 169 查看
刚毕业记得自己一直想做硬件,这也是大学时自己的想法。但工作中一切都是变化的,毕业快三年,学了一年硬件(基本也是慌了,学习的信号方面的知识比较多些吧),一次偶然的机会support嵌入式软件部门,最后干脆转去做嵌入式软件,从刚开始的几乎一无所知,到现在快两年,慢慢的入了门。但发现自己越来越无知。我想做什么事情都是要经历这样的过程吧: 简——〉繁——〉简,前几天公司项目上一个MSP430串口的底层驱动程序和提供给调用函数的接口函数,打包,加信息头,波特率的计算,checksum的计算和判断。到最后接受解包,判断校验和。由于是用到医疗产品上,安全性要求高,到最后接收函数的状态图画了快10次,真是感觉自己弱爆了。从刚开始画的太简单到最后画的越来越复杂,直到最后减去不必要的状态甚至更本不是状态,最后才写了一个较稳定的串口程序出来。实践很重要,C语言的基础也很重要啊!

于是决定仔细再学习C语言中的指针、链表、文件等知识,以谭浩强的C和K&R的C为读本。

以前只知道#include "filename.h" 这个filename.h一般是引用当前目录下的头文件。#include <filename.h>中的filename.h是编译器提供的库函数头文件活着C标准头文件。查询后得知:#include 指令指示编译器将xxx.xxx文件的全部内容插入此处。若用<>括起文件则在系统的INCLUDE目录中寻找文件,若用"
"括起文件则在当前目录中寻找文件。一般来说,该文件是后缀名为"h"或"cpp"的头文件。

注意:<>不会在当前目录下搜索头文件,如果我们不用<>而用""把头文件名扩起,其意义为在先在当前目录下搜索头文件,再在系统默认目录下搜索。

计算机队内存的管理是以“字”为单位的(一般操作系统以4个字节为一个“字”)。即使在一个“字”中只存放了一个字符,该“字”中的其他3个字节不会接着存放下一个数据,而会从下一个“字”开始存放数据。因此sizeof()函数测变量的长度时,得到的结果必然是4的倍数。

谭浩强版的C中的例子:

#include <stdio.h>

#include <stdlib.h>

struct Student

{

int num;

char* name;

float score;

};

int main()

{

struct Student student1, student2;

student1.name = (char *)malloc(20*sizeof(char));

student2.name = (char *)malloc(20*sizeof(char));

printf("please input the first student information: \n");

scanf("%d %s %f",&student1.num,student1.name,&student1.score);

printf("Please input the second student information: \n");

scanf("%d %s %f",&student2.num,student2.name,&student2.score);

if(student1.score > student2.score)

{

printf("The high score student is:\n%d\n%s\n%6.2f\n",student1.num, \

student1.name, student1.score);

}

else if(student1.score < student2.score)

{

printf("The high score student is:\n%d\n%s\n%6.2f\n",student2.num, \

student2.name, student2.score);

}

else

{

printf("The same score student is:\n%d\n%s\n%6.2f\n",student1.num, \

student1.name, student1.score);

printf("The same score student is:\n%d\n%s\n%6.2f\n",student2.num, \

student2.name, student2.score);

}

free(student1.name);

free(student2.name);

return 0;

}

如果只对该结构体变量student1和student2直接用scanf()函数:

scanf("%d %s %f",&student2.num,student2.name,&student2.score);

对其成员赋初值,可以编译通过,但是运行时就会发生错误!若将结构体类型定义为:

struct Student

{

int num;

char name[20];

float score;

};

则运行也正常,原因是:

编译器在编译时为 字符数组 分配了20个字节的存储空间,而对字符指针变量,只分配了一个存储单元,4个字节用于存放地址变量。但是该地址变量中存储的值却是不可预料的。再给它赋值就可能破会程序或者有用数据,幸亏有操作系统的保护,否则可能破会系统!

由于我用的是VC2010的编译环境所以要对malloc的(void*)类型进行强制转换。C环境是不需要强制类型转换了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: