C语言基础知识 ---------- 指针(pointer)、结构(structure)

版权声明:此为个人学习与研究成果,若需转载请提前告知。 https://blog.csdn.net/weixin_35811044/article/details/84886139

指针(pointer)

指针变量是一种特殊的变量,此变量存储的内容不是普通值(int double char......)而是其它变量的地址(address)。

  • 指针宣告:资料形态  *变量名   ---->    int  *ptr   、  char  *ptr   、double  *ptr   ......。
  • 取址算子: &变量名   ---->    int score = 85 ;  printf( "%d\n" , score ) ; printf( "%p\n" , &score) ;  结果:85 和 00022525FC(score变量在记忆体中存放的地址)。
  • 指针赋值:int score = 85 ; int *ptr ; ptr = & score; 即把变量score的地址赋值给了指针变量ptr。
  • 取值算子:*指针变量名 ---->   int score = 85 ; int *ptr ; ptr = & score ; printf( "%d" , *ptr ) ;  printf( "%p" , ptr ) ; 结果:85 和 00022525FC 。通过*取的指针所指地址的值,可以说 *ptr 就是变量 score;

注意:宣告指针变量时 用的(*) 表示的仅仅是: 此变量为指针没有其它意思,*后的变量名才是指针的名。 在取值时 用的(*) 是取值算子,不要弄混。

  • 数组指针: int tests[5] = {71,83,67,49,59} ; int *ptr  ; 若直接用数组名 tests 作为赋值,指向的是数组的第一个元素地址,tests = & tests[0]  ---->  ptr = tests 等于 ptr = &tests[0] 。对于数组指针可以进行加减法:若ptr = &tests[0] ,ptr+2 即指向 &tests[2] ;若ptr = &tests[3] ,ptr-2 即指向 &tests[1] 。

结构(structures)

结构就是自定义一个新的资料类型,有点像java里的实体类。

  • 结构宣告:关键字struct,结构中的变量为该结构的成员。

struct student{

 int id ;  char name[20] ;  int score;

}

  • 结构变量宣告: 未初始化:struct student std1 ;成员赋值使用 (.):std1.id = 1 ; strcpy(std1.name , "帅哥");std1.score = 90 ;初始化: struct student std2 = { 2 , " 帅哥 " , 90 }; 
  • 结构数组:struct student stds[3] ; 即有3个 stds[0] 、 stds[1] 、 stds[2] 。
  • 结构指标:基本一致,即指标存的是结构变量的地址。但指标类型也必须宣告成结构类型。特殊的是为成员赋值可使用 (->) 符号。

struct student std , *ptr ;   ptr = &std ;  

有两种成员赋值方式:ptr -> id = 2 ; (*ptr). score = 90 ; 

 

关键字typedef

就是用来为资料形态取别名的。

typedef  int  B ;  ---->  B numb = 5 ; 即这里 B 就是资料形态 int ,是 int 的别名。

  • 定义结构时: 

struct student{

          int a ;

}

typedef struct student Stu ;

为结构取了别名Stu,定义结构变量时:Stu std ; 或 struct student std 

typedef struct student{

             int a ;

}Stu

这里Stu就是结构 struct student 的别名,定义结构变量时:struct student std ;或 Stu std ;

student也可以不写,如:

typedef struct{

  int a ;

}Stu

那么此时定义此结构变量时只能:Stu std ; 这一种表示方式。

 

常数定义

两种方式:#define 和 关键字 const ;

  • ex.1        #define  常数名  值    --->   #define  PI  3.1415926
  • ex.2        const  资料形态  常数名 = 值   --->   const  double  PI = 3.14.15926 ;

常数是不可被更改,被赋值。

字串

C语言没有内建字串资料形态,C语言的字串就是一种char字符形态的一维数组,并使用 ‘ \0 ’ 标识字串结束。

  • char str[15] = "hello! world\n" ;
h e l l o !   w o r l d \n \0  
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

宣告一个字串,有15个元素,“\0”时结束字元,结束字元是占空间的需要预留一位。用strlen()求某字串长度是不包括“\0”,用sizeof求某字串长度是包含"\0"。输出格式是%s , printf("字串内容:%s\n",str)。

仅为个人理解,如有不足,请指教。 https://blog.csdn.net/weixin_35811044

猜你喜欢

转载自blog.csdn.net/weixin_35811044/article/details/84886139
今日推荐