C语言笔记_第七章

一、数组的运算
1.数组的大小
当我们有一个不确定大小的数组,我们需要得到它其中到底存放了多少元素
sizeof() 函数可以给出整个数组所占据的内容的大小单位是字节。

sizeof()函数是一个运算符,可以给出某个类型或者变量在内存中所占据的字节数
若数据总线32位:32bit比特=4Byte字节=1word字

eg:

#include <stdio.h>
int main(){
	int count;
	int test[1]={1};
	int number[]={3,4,5,6,7,8,11,24,35,26};
	printf("test数组一个元素占据大小:%d Byte \n",sizeof(test));
	//这里我们假设不知道number数组元素有几个
	printf("number数组存的元素有%d个\n",sizeof(number)/4);
	for(count=0;count<sizeof(number)/4;count++){
		printf("number[%d]=%d\n",count,number[count]);
	}
	return 0;
}

2.数组的赋值
数组变量本身不能被赋值,如果我们需要把一个数组内的元素,原封不动的转移到另外一个数组必须采用遍历的
方式对数组进行遍历。
eg:
这里我们将number数组里面的内容放到transfer数组里面。

#include <stdio.h>
int main(){
int number[]={3,4,5,6,7,8,11,24,35,26};
int transfer[sizeof(number)/4];
int count;
for(count=0;count<sizeof(number)/4;count++){
	transfer[count] = number[count];
}
for(count=0;count<sizeof(number)/4;count++){
		printf("transfer[%d]=%d\n",count,transfer[count]);
	}
return 0;
}

二、搜索
假如说我们存在一个二维数组我们需要去寻找在二维数组当中匹配的数据。
eg:

#include<stdio.h>
#define line 5//作用全局定义 类似于一个标号 遇到line 之后就会替换为5
int search(int target,int pixel[][line],int row,int tandem);
int main(){
int goal;
int pixel[][line]={
	{1,2,3,4,5},
	{6,7,8,9,10},
	{11,12,13,14,15}
};
printf("请输入您要寻找的像素点:\n");
scanf("%d",&goal);
if(search(goal,pixel,sizeof(pixel)/(sizeof(pixel[0][0])*line),line)==-1){
	printf("未找到您所需的像素点\n");
}
return 0;
}
int search(int target,int pixel[][line],int row,int tandem){
	//printf("%d %d",row,tandem);
	int ret=-1;
	int r;
	int t;
	for(r=0;r<row;r++){
		for(t=0;t<tandem;t++){
			if(target==pixel[r][t]){
				ret=1;
				printf("您寻找的像素点已经找到,在二维阵列的%d行,%d列.\n",r+1,t+1);
				break;
			}
		}
	}
	return ret;
}

三、完成映射关系(类似哈希函数)
我们这里有一些像素点,不同的像素点对应不同的值,我们需要如何去做呢。
尽量不要使用割裂的数组进行匹配,对cache不友好。
eg:red:1 green:2 blue:3

#include <stdio.h>
int main(){
	int target;
	int count;
	int lose=1;
	char *name[]={"red","green","blue"};
		struct{              //结构体 可以包含多种不同的数据类型
			int pixel;
			char *name;
		} gather[]={
			{1,"red"},
			{2,"green"},
			{3,"bule"}
		};                  //重新定义数组
		printf("请输入您要查找的像素值:\n");
		scanf("%d",&target);
		for(count=0;count<sizeof(gather)/sizeof(gather[0]);count++){
			if(target==gather[count].pixel){
				printf("所对应的像素为:%s\n",gather[count].name);
				lose=0;
				break;				
			}
		}
		if(lose==1){
			printf("对不起没有找到!\n");
		}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值