C语言自定义函数的形参为数组时需要注意传入长度

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 /*
 4     程序运行结果:
 5     False sort
 6     length=1
 7     4
 8     Right sort
 9     length=5
10     4 5 7 8 9
11 */
12 /*
13     个人总结:
14     C/C++ 传递数组,
15     虽然传递的是首地址地址,
16     但是参数到了函数内,就成了普通指针,
17     不再是数组首地址了,
18     所以试图在别的函数中无法得到传递数组的长度。
19     只能先计算好长度后再传过去。
20 */
21 void false_sort(int a[]){
22     int length=sizeof(a)/sizeof(a[0]);
23     printf("length=%d\n",length);//输出为1
24     for(int i=0;i<length-1;i++){
25         for(int j=0;j<length-1-i;j++)
26             if(a[j]>a[j+1]){
27                 int temp=0;
28                 temp=a[j];
29                 a[j]=a[j+1];
30                 a[j+1]=temp;
31             }
32     }
33     //printf("%s\n",a);
34     for(int i=0;i<length;i++){
35         printf("%d ",a[i]);
36     }
37 }
38 //void right_sort(int a[],int length){
39 void right_sort(int *a,int length){
40     printf("length=%d\n",length);
41     for(int i=0;i<length-1;i++){
42         for(int j=0;j<length-1-i;j++)
43             if(a[j]>a[j+1]){
44                 int temp=0;
45                 temp=a[j];
46                 a[j]=a[j+1];
47                 a[j+1]=temp;
48             }
49     }
50     //printf("%s\n",a);
51     for(int i=0;i<length;i++){
52         printf("%d ",a[i]);
53     }
54 }
55 int main()
56 {
57     int a[]={4,5,8,7,9};
58     //char b[]={"This is a string!"};
59     int length=sizeof(a)/sizeof(int);
60     //printf("%d\n",sizeof(b)-1);
61     printf("False sort\n");
62     false_sort(a);
63     printf("\nRight sort\n");
64     right_sort(a,length);
65     return 0;
66 }

猜你喜欢

转载自www.cnblogs.com/stefango/p/9633844.html