# 【学习ios之路:C语言】一维数组,数组排序,字符数组

1.数组

```%lu  unsigned long 无符号的长整型. 无符号 >=0
sizeof 存储大小值  //用来计算一个变量,类型,以及数组所占存储空间的大小.
int a[5] = { 2, 7, 4, 3, 6 };
printf("%lu\n", sizeof(arr)); //5
int b[5] = { 2, 7, 4 }; printf("%lu\n", sizeof(arr)); //5
int c[5] = { 0 }; printf("%lu\n", sizeof(arr)); //5,因为定义的空间大小为5
int d[] = { 2, 7, 4, 3, 6 }; printf("%lu\n", sizeof(arr)); //5```
`</pre><pre>`

```arr[5] = 20;
printf("%d",arr[5]);//角标越界```

1. 字符串所占的 空间 ⾄少要比 字符串⻓度 大1，因为字符串以‘\0’表⽰示结束。系统提供的字符串处理函数都是根据‘\0’来判断字符串是否结束。

```char arr[] = "ipho";
printf("%lu\n", sizeof(arr)); //存储空间大小为 5,因为有默认的\0   <pre name="code" class="cpp"><pre name="code" class="cpp">     printf("%lu\n", strlen(arr)); //字符串长度为 4```

1.讲数组中的每一个元素输出

```int arr[5] = {1, 3, 5, 6, 7};
for (int i = 0; i < 5 ; i++) {
printf("%d\n", arr[i]);
}```

2.给数组中的每一个元素赋值 [20, 40]

```int a[10] = {0};
for (int i = 0 ; i < 10; i++) {
a[i] = arc4random() % (40 - 20 + 1) + 20;
printf("a[%d] is %d\n", i, a[i]);
}```

3.求数组中的最小值,给数组中的每一个元素赋值 [20 , 40].

```int a[10] ={0};</span>
<span style="color:#000000;">for (int i = 0 ; i < 10; i++) {
a[i] = arc4random() % (40 - 20 + 1) + 20;
printf("a[%d] is %d\n", i, a[i]);
}

int  min = 0;
for (int i = 0; i < 10; i++) {
if (i == 0) {
min =a[0];
} else {
if (min > a[i]) {
min = a[i];
}
}
}
printf("最大值为:%d\n", min);```

4. 定义 一个10位数组,数组中的元素取值范围为[30,50],求所有元素的和.

```int arr[10] = {0};
for (int i = 0 ; i < 10 ; i++) {
arr[i] = arc4random() % ( 50 - 30 + 1 ) + 30;
printf("%d\n",arr[i]);
}
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += arr[i];
}
printf("所有元素之和为:%d\n", sum);```

2.数组排序

```int  a[10] = {0};
for (int i = 0; i < 10; i++) {
a[i] = arc4random() % (15 - 10 + 1 ) + 10;
printf("%d  ", a[i]);
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 10 - 1 - i ; j++) {
if (a[j] < a[j+1]) { //降序排列
int  temp  =a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("\n");
for (int  i = 0; i < 10 ; i++) {
printf("%d  " ,a[i]);
}```

3.字符数组

char str[4]= {'F', 'R','','L','N'};
printf("%lu\n",sizeof(str5));

char str[] = "phone"; //字符串

```char str5[]= {'F', 'R', 'L', 'N','d'};//如果定义空间大小[6],sizeof为6,长度为5
char str6[]="frln";
printf("str5 = %lu\n",sizeof(str5));  //空间大小为5
printf("str6 = %lu\n",sizeof(str6)); // 空间大小为5,隐藏\0
printf("str5 =%lu\n",strlen(str5)); // 长度5
printf("str33 =%s\n",str5); // FRLND
printf("str44 =%s\n",str6); // frln
printf("str6 =%lu\n",strlen(str6)); // 长度4```

char str[] = "iphone";

printf("%s\n", &str[4]);//取出 ne,从第四个开始,取出以后的内容

printf("%c\n",str[4]);

3.字符串处理

```	char str[10] = "language";
//字符串的长度.
printf("%lu\n", strlen(str)); //8

//字符串拷贝
strcpy(str ,"aa");
printf("%s\n",str); //因为有隐藏字符 \0,所以只能打印出aa.
//字符串 拼接
strcat(str,"bb");
printf("%s\n",str);//因为有隐藏字符 \0,所以只能打印出aabb.但是后面还存在值,如下
printf("%c\n",str[6]); // 结果为g

//字符串比较
printf("%d\n",strcmp("aa","bb"));		//  b - a = -1
printf("%d\n",strcmp("da","bb"));	   //  (d -b) + (b - a ) =2
printf("%d\n",strcmp("bba","bb"));	 //如上 97```