C *运算符在数组赋值中的含义

时间:2009-12-12 22:32:59

标签: c arrays pointers variable-assignment

这条线是什么意思?几年后我没有做过C。它是否在parens中执行操作然后使int结果成为指针?

b[0] = *(start + pos++);

5 个答案:

答案 0 :(得分:8)

显然start是一个指针(或数组,无论如何都会衰减到指针),这意味着()中表达式的结果是一个指针,而不是{{1 }}。 int只是取消引用该指针。

整个事情等同于普通*,但由于某些原因,有些人更喜欢使用模糊的表格,如你的帖子。

答案 1 :(得分:5)

假设start是指针而pos是一个整数,它可以很容易地重写为:

b[0] = start[pos++];

希望这有助于您理解。

答案 2 :(得分:3)

为此,startpos必须是指针;最有可能的是,start。然后可以将代码写为

b[0] = start[pos];
pos = pos + 1;

实际上,即使pos是指针,代码也是等价的,因为C的数组订阅有点滑稽的语义。

答案 3 :(得分:2)

运算符'*'返回操作符后面的指针或表达式所指向的位置的值。

一些例子:

value = *pointer;
value = *(pointer);     // Exactly the same as the first statement.
value = *(pointer + 0); // Take contents of pointer and add zero then dereference.
value = *(pointer + 1); // Deference the first location after the location in pointer.

有时,特别是在嵌入式系统中,这比使用数组表示法更具可读性。示例:status = *(UART + STATUS_REGISTER_OFFSET);

答案 4 :(得分:1)

注意这些表达式的等价性。首先,假设以下声明确定了正在使用的类型:

T* const base;
size_t const pos;

现在,T类型的对象位于内存

base + sizeof(T) * pos

可以通过多种方式访问​​:

base[pos]                            // Interpret base as an array.
*(base + pos)                        // Pointer arithmetic strides by sizeof(T)
*(T*)((char*)base + sizeof(T) * pos) // Compute stride manually
相关问题