通过指针间接赋值的意义
- 开发过程中,离不开指针,指针出现的意义有很多,其中一种通过方法去修改值。
- c和java的方法不同所在,c可以传对象的地址在方法里面去赋值,java一般都是通过返回值
我们模拟一下指针方法赋值的写法
typedef struct {
int width;
int height;
int format;
} AndroidBitmapInfo;
void AndroidBitma_getInfo(AndroidBitmapInfo *bitmap) {
//通过指针在方法里面赋值
bitmap->width = 300;
bitmap->height = 600;
bitmap->format=556;
};
void main(){
AndroidBitmapInfo androidBitmapInfo;
AndroidBitma_getInfo(&androidBitmapInfo);
printf("width=%d,height=%d", androidBitmapInfo.width, androidBitmapInfo.height);
getchar();
}
野指针
野指针指向一个已删除的对象或未申请访问受限内存区域的指针。与空指针不同,野指针无法通过简单地判断是否为 NULL避免
AndroidBitmapInfo *androidBitmapInfo=(AndroidBitmapInfo*)malloc(sizeof(AndroidBitmapInfo));
AndroidBitma_getInfo(&androidBitmapInfo);
printf("width=%d,height=%d",androidBitmapInfo->width,androidBitmapInfo->height);
//释放
if(androidBitmapInfo!=NULL){
free(androidBitmapInfo);
//避免出现野指针的情况,减少程序代码出错
androidBitmapInfo=NULL;
}
//若再次释放,会有问题
if(androidBitmapInfo!=NULL){
free(androidBitmapInfo);
}
NULL地址
指针指向NULL,相当于指向0x00000000,但是我们不能去操作这块地方,这块地方是c和c++编译器持有的。
//写入位置会访问报错,NULL也是一个地方,指针指向NULL,相当于指向0x00000000
//但是我们不能去操作这块地方,这块地方是c和c++编译器持有的
char *p1 = NULL;
strcpy(p1, "1122");
字符串不同之处
//字符串的几种区别
// char buff[100]={'P','e','a','k','m','a','i','n'};//后面的都是默认值0
//char buff1[8]={'P','e','a','k','m','a','i','n'};
// char buff2[]={'P','e','a','k','m','a','i','n'};//size是8(默认是里面的个数)
//char buff3[100]={0};//把数组初始化为0
//char buff[50];//数据都是默认值-52'
//char buff[]="123456";//len是6,size是7
//相当于 char buff[]={1,2,3,4,5,6,\0};
char* buff="123456";
// char buff[]="123456"和 char* buff="123456"区别
//字符串在任意地方开辟内存,栈区,堆区,常量区
//大小
int len=strlen(buff);//8,遇到'\0'就结束了
int size= sizeof(buff);//100
printf("len=%d,size=%d\n",len,size);
//内容
printf("%d,%d,%d\n",buff[0],buff[66],buff[99]);//100,0,0
getchar();
项目开发模型强化
设计一个获取Bitmap属性的函数
1.确定你的参数,传递指针
2.一定要考虑它的健壮性
3.要把异常错误进行抛出说明
4.不要直接轻易去改变调用传递给你的指针
typedef struct {
int width;
int height;
int format;
} AndroidBitmapInfo;
int AndroidBitma_getInfo(AndroidBitmapInfo *bitmapInfo) {
//可能会对bitmapInfo进行再次赋值
int res = 0;
if (bitmapInfo == NULL) {
printf("bitmapInfo is NULL,无法进行操作,错误码:%d", -1);
return -1;
}
//可能还会有-2的错误,一般0代表正常情况
//通过指针在方法里面赋值
bitmapInfo->width = 300;
bitmapInfo->height = 600;
bitmapInfo->format = 556;
return res;
};
void main(){
AndroidBitmapInfo *androidBitmapInfo = (AndroidBitmapInfo *) malloc(sizeof(AndroidBitmapInfo));
AndroidBitma_getInfo(&androidBitmapInfo);
int res = AndroidBitma_getInfo(androidBitmapInfo);
if (res == 0) {
printf("width=%d,height=%d", androidBitmapInfo->width, androidBitmapInfo->height);
}
//释放
if (androidBitmapInfo != NULL) {
free(androidBitmapInfo);
//避免出现野指针的情况,减少程序代码出错
androidBitmapInfo = NULL;
}
getchar();
}
//4.不要直接轻易去改变调用传递给你的指针
int strlen(char *str) {
//临时变量
char *countStr=str;
int count = 0;
while (*countStr) {//相当于不等于'\0'
countStr++;
count++;
}
//自己想看看结果对不对
printf("str=%s,len=%d\n", str, count);
return count;
}
void main() {
char *str = "123456";
int len = strlen(str);
printf("len=%d", len);
getchar();
}