Re: [问题] 指标

楼主: OPIV (Monitor)   2015-06-17 15:14:47
※ 引述《GooLoo (平凡)》之铭言:
: 开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
: 额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
: 问题(Question):
: 请问一下
: *与&最大不同是
: *a : a的内容 &a : a的位址
: 最近在看一份范例程式,它用了很多指标,
: 我想了解程式内容,并用自己看得懂的方式重写
: 其中,
: uint16_t moved_perm(uint8_t *buf)
: {
: uint16_t plen;
: plen=fill_a(buf,0,PSTR("123"));
: return(plen);
: }
: *buf =>动作不是很懂 ,平常写都没星号,
: 有人可以举例说明, 差异跟应该会得到的结果吗?
: 我google过, 多半看不懂, 或是只教*与&的不同,
: 针对函式中的参数有星号没有特别的说明
: 可否请高手指点, 这种参数内有指标的意义
: 另外buf应该是一个阵列?那可以带到函式参数内?
: 谢谢
: 喂入的资料(Input):
: 预期的正确结果(Expected Output):
: 错误结果(Wrong Output):
: 程式码(Code):(请善用置底文网页, 记得排版)
: 补充说明(Supplement):
你的问题去书上找"变量"应该会有答案
在这里分享我当初是怎么搞懂指标的(仅限语法上)希望对你有帮助
首先 一个变量包含这些东西
1. 变量名称
2. 变量型态
3. 变量在内存中的位址
4. 变量的值
1. 变量名称只在程式码里有意义,简单来说就是让你可以用一个名子来操作内存
2. 告诉程式这个变量需要多少内存,要怎么转成人看得懂的格式 etc......
3. 变量要放东西进去一定要有个空间,内存位址就是系统分配给变量的空间的位址
4. 变量的内容就看你要放什么东西进去了,变量的值的意义只有你自己懂,纯看你如何
用它
那首先看怎么宣告变量(可以去参考 right-left rule)
宣告型态为 (int) 的变量
int a; // (int) a,a 的型态是(int)
int b; // (int) b,b 的型态是(int)
int c; // (int) c ,c 的型态是(int)
宣告型态为 (int *) 的变量
int *a; // (int *) a,变量 a 的型态是 (int *),(int) *a,变量 *a 的型态是(i
nt)
int *b; // (int *) b 打字好累
int *c; // (int *) c 打字好累
宣告型态为 (struct Node) 的变量
struct Node a; // @#~!*&#^&@
struct Node b;ꀠꀠ// @#~!*&#^&@
struct Node c;ꀠꀠ// @#~!*&#^&@
看出来了没?
来举个例子:
struct Node *node = NULL;
node 的型态是 (struct Node *) // (struct Node *)node = NULL
*node 的型态是 (struct Node) // (struct Node) *node = NULL
所以 node 里装的是 NULL,*node 的值就是 NULL 这个位址里的型态为(struct Node)的
变量的值(当然,这个位址可能是 alloc 来的,不属于别的变量)
第一种常见的指标用法:
struct Node node = {NULL, NULL, 0}; // 先宣告一个一般的变量
struct Node *node_ptr = &node; // 再宣告一个指标,把一般变量的位址存进指标

来看看变量们的详细内容:
node:
node 的型态:struct Node
node 的内存位址:&node
node 的值:{NULL, NULL, 0}
node_ptr:
node_ptr 的型态:struct Node *
node_ptr 的内存位址:&node_ptr
node_ptr 的值:&node
第二种常见用法:
struct Node *node_ptr = (struct Node)malloc(sizeof(struct Node)); // 向系统
取得一块大小为sizeof(struct Node)的内存,再把位址塞到 node_ptr 里面
再看一次变量的资料:
*node_ptr:
*node_ptr 的型态:struct Node
*node_ptr 的内存位址:没有这种东东
*node_ptr 的值:系统分内存给你的时候里面装了什么,你拿到里面就是什么(只有全
域变量会自动初始化)
node_ptr:
node_ptr 的型态:struct Node *
node_ptr 的内存位址:&node_ptr
node_ptr 的值:malloc 传回来的位址
简单的变量型态就把前面括起来,型态就出来了
(int *) a, b, c;
(const char *const) a;
(const char)* const a;
如果是函式指标,就用 right-left rule 吧!

Links booklink

Contact Us: admin [ a t ] ucptt.com