C語言字符指針和字符數組

剛畢業記得自己一直想做硬件,這也是大學時自己的想法。但工作中一切都是變化的,畢業快三年,學了一年硬件(基本也是慌了,學習的信號方面的知識比較多些吧),一次偶然的機會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環境是不需要強制類型轉換了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章