一、資料型別
1.1 基本資料型別
整型:int, long,unsigned int,unsigned long,long long……
字符型:char
浮點型:float, double……
【例子】
//no.1
int a,b,c;
a = 1;
b = 2;
c = a + b;
//no.2
char s;
s = ‘a’;
float f;
f = 3.1415;
1.2 結構體型別
定義:用系統已有的不同基本資料型別或者用戶自定義的結構型組合成的用戶需要的復雜資料型別,
【例子】
struct Student{
int num;
char name[20];
int age;
float score;
};
struct Student s1,s2;
s1.num = 101;
s2.num = 102;
改進:指定新的型別名來代替已有的型別名
typedef int Integer;
typedef float Real;
int i,j; ——>Integer i,j;
float a,b; ——>Real a,b;
使用typedef改進結構體
typedef struct Student{
int num;
char name[20];
int age;
float score;
}Student;
Student s1,s2;
s1.num = 101;
s2.num = 102;
1.3 指標型別
一個變數的地址稱為該變數的“指標”,專門存放變數地址的一類變數成為“指標變數”
【例子】
//no.1
int *a;
int b = 0;
a = &b;
*a = 1; ——>b = 1;
//no.2
char *c;
char d = ‘a’;
c = &d;
*c = ‘A’; ——>d = ‘A’;
//no.3
typedef struct Student{
int num;
char name[20];
int age;
float score;
}Student;
Student s1;
Student *s1_p;
s1_p = &s1;
s1.age = 23; ——> (*s1_p).age = 23;
——> s1_p->age = 23;
二、函式
2.1 被傳入函式的引數是否會改變,執行結果是多少,為什么?
//no.1
void fun(int num){
num++;
}
int a = 1;
fun(a);
printf(“%d”,a);
//no.2
void fun(int &num){
num++;
}
int a = 1;
fun(a);
printf(“%d”,a);
//no.3
void fun(int a[]){
a[0]++;
}
int a[10];
a[0] = 1;
fun(a);
printf(“%d”,a[0]);
2.2 帶回傳值的函式
int fun(int a, int b)
{
int c;
c = a+b;
return c;
}
int res = fun(1,1);
printf("%d",res); ——> printf("%d",fun(1,1));
三、動態記憶體分配
3.1 使用malloc函式分配空間
函式原型:void *malloc(unsigned int size);
函式作用:在記憶體的動態存盤區中分配一個長度為size的連續空間,并回傳所分配第一個位元組的地址
float *f = (float *)malloc(4);
char *c = (char *)malloc(1);
Student *s1_p = (Student *)malloc( ??);
改進:使用sizeof配合malloc分配
定義:sizeof是測量型別或者變數長度的運算子
int num1 = sizeof(float);
int num2 = sizeof(char);
int num3 = sizeof(Student);
float *f = (float *)malloc(sizeof(float));
char *c = (char *)malloc(sizeof(char));
Student *s1_p = (Student *)malloc(sizeof(Student));
3.2 使用free函式釋放空間
函式原型:void free(void *p);
函式作用:釋放指標變數p所指向的動態空間,使這部分空間可以被其他變數使用
float *f = (float *)malloc(sizeof(float));
char *c = (char *)malloc(sizeof(char));
Student *s1_p = (Student *)malloc(sizeof(Student));、
……//此處省略部分操作
free(f);
free(c);
free(s1_p);
查看更多
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/77842.html
標籤:其他
下一篇:ps學習
