是否有可能在索引不是零的情况下启动一个数组... IE你有一个数组a [35],35个元素,现在我想索引说起始100,所以数字将是[100],a [101],...... a [134],这可能吗?
我正在尝试为一块电路板生成一个"存储器映射",我将有一个名为SRAM [10000]的阵列和另一个名为BRAM [5000]的阵列,但在"内存"可视性中它们是连续的,IE BRAM在SRAM之后立即启动,因此如果我尝试指向内存位置11000,我会读它看到它超过10000然后将它传递给bram.
打字时我意识到我可以假设然后从数字中减去10K并将其传递给BRAM,但为了争论,这是否可以将11000传递给BRAM?
感谢您的任何帮助.
更新以修复a [34]到[134]
更新了更多信息:在我将要实现的实际架构中,sram和bram之间可能存在差异,例如地址11008可能在内存映射中不可见,因此编写一个充满内存的巨型数组然后"分区"它会起作用,但我仍然需要做逻辑来确定它是否在"sram和bram"的范围内.这首先是我想要避免的.
Han*_*s W 19
是否有可能在索引不是零的情况下启动一个数组... IE你有一个数组a [35],35个元素,现在我想索引说起始100,所以数字将是[100],a [101],...... a [134],这可能吗?
不,你不能在C中做到这一点.数组总是从零开始.在C++中,您可以编写自己的类,说明OffsetArray并重载运[]算符以访问底层数组,同时从索引中减去偏移量.
我正在尝试为一块电路板生成一个"存储器映射",我将有一个名为SRAM [10000]的阵列和另一个名为BRAM [5000]的阵列,但在"内存"可视性中它们是连续的,IE BRAM在SRAM之后立即启动,因此如果我尝试指向内存位置11000,我会读它看到它超过10000然后将它传递给bram.
你可以尝试这样的事情:
char memory[150000];
char *sram = &memory[0];
char *bram = &memory[100000];
Run Code Online (Sandbox Code Playgroud)
现在,当您访问时,sram[110000]您将访问"在bram"中的内容
Jer*_*fin 13
在这方面,C++提供了比C更多的东西.您可以重载operator[]以进行减法,如果您想要报告错误(例如,抛出异常),如果下标超出范围.
我记得读过"专家C编程 - 深度C秘密"这本书,Peter Van der Linden披露了一个欺骗编译器思考数组偏移从1开始的技巧......理论上可以完成这个技巧,我没有这本书和我一起,但是随便,我记得读它......它不便携,可能产生不明确的行为......
编辑:请参阅C-FAQ上的第6.17节.警告:不可移植和未定义的行为!从这里引用来源.
6.17: Here's a neat trick:
if I write int realarray[10];
int *array = &realarray[-1];
I can treat "array" as if it were a 1-based array. A: Although this technique
is attractive (and was used in old editions of the book _Numerical Recipes in C_),
it is not strictly conforming to the C Standard. Pointer arithmetic is defined
only as long as the pointer points within the same allocated block of memory,
or to the imaginary "terminating" element one past it; otherwise, the behavior
is undefined, *even if the pointer is not dereferenced*. The code above could
fail if, while subtracting the offset, an illegal address were generated
(perhaps because the address tried to "wrap around" past the beginning of some
memory segment).
References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6;
ISO Sec. 6.3.6; Rationale Sec. 3.2.2.3.
Read more: http://www.faqs.org/faqs/C-faq/faq/#ixzz0ftyqHOvm
希望这可以帮助.
你可以欺骗宏:
int myarray[35];
#define a (myarray - 100)
a[100] = 0;
Run Code Online (Sandbox Code Playgroud)
也可以使用指针.
不 - 因为你不能像VB6那样修改声明中的下限.
是的 - 就像你可以做的那样
int a[35];
int* actual_a = a-100;
printf("%d", actual_a[101]);
...
Run Code Online (Sandbox Code Playgroud)
因为x[a]相当于*(x+a).这是非常不推荐的.