文章目录
1. 不能直接将数组赋值给另一个数组
#include <stdio.h>
int main() {
int array[] = { 0, 1, 2, 3, 4 };
int array2[5] = array;
int i = 0;
for (i = 0; i < sizeof(array2) / sizeof(int); i++) {
printf("%d ", array2[i]);
}
return 0;
}
像上面的代码是会报错的,因为数组名是数组的首地址,于是上述操作只是将数组的地址作为等式的右边,而左边准备接收的是一串数字。
2. 不能将数组作为返回值
3.结构体变量不能以. 或 ->的形式作为函数形式参数或返回值,因为不是变量类型
4. 不能在函数里面用sizeof求形参数组的大小
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int binary_search(int array[], int key);
int main()
{
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
printf("Give the number you want to search > ");
int num = 0;
while (scanf("%d", &num) == 1)
{
if (binary_search(arr, num))
{
printf("The number %d you search is not in this array.\n", num);
}
printf("Give the number you want to search > ");
}
return 0;
}
int binary_search(int array[], int key)
{
int left = 0;
int right = sizeof(array) / sizeof(int) - 1;
int mid = (left + right) / 2;
int flag = 1;
while (left <= right)
{
mid = (left + right) / 2;
if (array[mid] < key)
{
right = mid - 1;
}
else if (array[mid] > key)
{
left = mid + 1;
}
else
{
printf("The number %d is in index %d\n", key, mid);
flag = 0;
break;
}
}
return flag;
}
如上面的代码,在这里面编译器会说Dividing sizeof a pointer by another value.意思是形参arr只是一个指针变量而不是一个
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int binary_search(int array[], int key, int sz);
int main()
{
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
printf("Give the number you want to search > ");
int num = 0;
while (scanf("%d", &num) == 1)
{
if (binary_search(arr, num, sizeof(arr) / sizeof(int)))
{
printf("The number %d you search is not in this array.\n", num);
}
printf("Give the number you want to search > ");
}
return 0;
}
int binary_search(int array[], int key, int sz)
{
int left = 0;
int right = sz - 1;
int mid = 0;
int flag = 1;
while (left <= right)
{
mid = (left + right) / 2;
if (array[mid] < key)
{
right = mid - 1;
}
else if (array[mid] > key)
{
left = mid + 1;
}
else
{
printf("The number %d is in index %d\n", key, mid);
flag = 0;
break;
}
}
return flag;
}
但是可以在函数值用sizeof对整型形参进行求大小
int binary_search(int array[], int key, int sz)
{
int left = 0;
int right = sz - 1;
int mid = 0;
int flag = 1;
int a = sizeof(key) / sizeof(int); //这样是不会报警告的,因为key在这里是值而不是指针
printf("%d\n", a);
while (left <= right)
{
mid = (left + right) / 2;
if (array[mid] < key)
{
right = mid - 1;
}
else if (array[mid] > key)
{
left = mid + 1;
}
else
{
printf("The number %d is in index %d\n", key, mid);
flag = 0;
break;
}
}
return flag;
}
这样是不会报警告的,因为key在这里是值而不是指针。
通过这样会发现在传数组参数时array接收的只是数组第一元素的地址(数组的首地址)。