- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类和对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类
- Objective-C - 伪装
- Objective-C - 扩展
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 中函数的指针返回值
正如我们在上一章中看到的,Objective-C 编程语言允许从函数中返回一个数组,类似地,Objective-C 允许您从函数中返回一个指针。为此,您必须声明一个返回指针的函数,如下例所示:
int * myFunction() {
.
.
.
}
第二个需要记住的是,将局部变量的地址返回到函数外部不是一个好主意,因此您必须将局部变量定义为静态变量。
现在,考虑以下函数,它将生成 10 个随机数,并使用一个数组名称(表示指针,即第一个数组元素的地址)返回它们。
#import <Foundation/Foundation.h>
/* function to generate and return random numbers. */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
NSLog(@"%d\n", r[i] );
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
NSLog(@"*(p + [%d]) : %d\n", i, *(p + i) );
}
return 0;
}
当以上代码编译并执行时,会产生如下结果:
2013-09-13 23:32:30.934 demo[31106] 1751348405 2013-09-13 23:32:30.934 demo[31106] 1361314626 2013-09-13 23:32:30.934 demo[31106] 833264711 2013-09-13 23:32:30.934 demo[31106] 1700550876 2013-09-13 23:32:30.934 demo[31106] 1164219218 2013-09-13 23:32:30.934 demo[31106] 1083527138 2013-09-13 23:32:30.934 demo[31106] 1465344952 2013-09-13 23:32:30.934 demo[31106] 849888001 2013-09-13 23:32:30.934 demo[31106] 1220494938 2013-09-13 23:32:30.934 demo[31106] 2095604466 2013-09-13 23:32:30.934 demo[31106] *(p + [0]) : 1751348405 2013-09-13 23:32:30.934 demo[31106] *(p + [1]) : 1361314626 2013-09-13 23:32:30.934 demo[31106] *(p + [2]) : 833264711 2013-09-13 23:32:30.934 demo[31106] *(p + [3]) : 1700550876 2013-09-13 23:32:30.934 demo[31106] *(p + [4]) : 1164219218 2013-09-13 23:32:30.934 demo[31106] *(p + [5]) : 1083527138 2013-09-13 23:32:30.934 demo[31106] *(p + [6]) : 1465344952 2013-09-13 23:32:30.934 demo[31106] *(p + [7]) : 849888001 2013-09-13 23:32:30.934 demo[31106] *(p + [8]) : 1220494938 2013-09-13 23:32:30.934 demo[31106] *(p + [9]) : 2095604466
objective_c_pointers.htm
广告