11.10

用sizeof求阵列长度

  1. #include<stdio.h>
  2. int main(){
  3. int a[3]={1,2,3};
  4. printf("size of int:%zu\n",sizeof(a[0]));
  5. printf("size of a:%zu\n",sizeof(a));
  6. printf("length of a:%zu\n",sizeof(a)/sizeof(a[0]));
  7. return 0;
  8. }

利用此来计算阵列长度

放在函式中时,计算结果会出现错误,因为函式中的并不是阵列,而是另一种格式

用保留值标记阵列长度

  1. #include<stdio.h>
  2. int length(int[]);
  3. int main(){
  4. int a[4]={3,9,7,-1}; //将-1作为特殊的标记值
  5. printf("%d\n",length[a]);
  6. return 0;
  7. }
  8. int length(int a[]){
  9. int i=0;
  10. while(a[i]!=-1){
  11. i++
  12. }
  13. return i;
  14. }

函式中不能包含标记值

可以用标记值来做结束一段语句的标志

函式间传递阵列的原理

其实存储的是阵列第一个元素的起始位置

a[i]的起始位置=的一个元素的起始位置+i*sizeof(int)

字串

  1. #include<stdio.h>
  2. void str_print(char str[]){
  3. printf("%s\n",str); //用%s来输出
  4. }
  5. int main(){
  6. char str[]="hello world"; //简化前为={'h','e','l','l','o',' ','w','o','r','l','d','\0'}
  7. str_print(str); //字串是以'\0'表示结尾的字元阵列
  8. return 0;
  9. }