You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AVR C:const限定符在数组式查找表中的行为解析

Understanding const with Arrays in C

Hey Carlos, great question — this is one of the most common pitfalls when learning C, so you’re definitely not alone in this confusion! Let’s break this down step by step to clear things up.

First: Arrays Are Not Pointers

Your core misunderstanding here comes from assuming arrays are identical to pointers — they’re not! While array names decay (implicitly convert) to pointers to their first element in most contexts, they’re fundamentally different types. An array has a fixed size and occupies a contiguous block of memory, whereas a pointer is a variable that holds a memory address.

What const uint8_t data[] = { ... } Actually Means

When you declare an array with const like this:

const uint8_t data[] = { 15, 3, 41, 76, 2, 9, 5 };

The const qualifier applies to each element of the array, not to a "pointer" representing the array. This means:

  • You cannot modify any element of data (e.g., data[2] = 100; will throw a compiler error)
  • Reading elements (like val = data[5];) is totally allowed — const only restricts writes, not reads
  • The array name data itself is an immutable l-value (you can’t do data++ or reassign it to point elsewhere, which is different from a regular pointer)

How This Differs from const Pointers

To clarify the distinction, let’s compare with pointer declarations:

  • const uint8_t *ptr = data;: This is a pointer to const uint8_t. You can change where ptr points (e.g., ptr++ to point to the next element), but you can’t modify the data it points to.
  • uint8_t *const ptr = data;: This is a const pointer to uint8_t. You can’t change where ptr points, but you can modify the data at that address.
  • const uint8_t *const ptr = data;: A const pointer to const data — neither the pointer nor the data can be modified.

Recapping Your Original Question

Your initial thought that "pointer itself不可修改但内容可改" applies to the uint8_t *const ptr case, not to the array declaration. For the array with const, the reverse is true: the elements (content) are read-only, and the array’s "identity" (its base address) can’t be changed either (since it’s not a variable pointer).

内容的提问来源于stack exchange,提问作者Carlos M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:15:07