gpt4 book ai didi

char** C 中的数组越界行为

转载 作者:行者123 更新时间:2023-11-30 19:01:23 24 4
gpt4 key购买 nike

有人可以解释一下,对于二维数组,当您超出索引范围但在初始化内存内时,C 中会发生什么吗?

例如:

    char t[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

for (int i = 0; i < 6; i++)
{
printf("%i\n", t[0][i]); //prints 1 thru 6 on separate lines
}

按预期工作,但是

//gcc 5.4.0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char* s[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

/*
printf("%i\n", s);
printf("%i\n",(s+1));
printf("%i\n",(s+2));
printf("%i\n", (s+3));
printf("%i\n", (s+4));
*/

for (int i = 0; i < 20; i++)
{
printf("%c\n", s[0][i]);
}

return 0;

/* Output:
.
-

.
.
.
-

-
.
.
-

-
.
-
-

-
-
*/


显示每个“字符串”分配了 8 个字节的连续内存,但字符在数组中出现时并不连续打印(摩尔斯电码) - 前 2 个字符来自 s[0],但最后一个字符来自 s[0]是从数组的末尾开始的。

最佳答案

s 不是二维数组。您没有将字符串存储在s中 - 您将每个字符串的第一个字符的地址存储在s<中 (在您的计算机上,char * 的宽度为 8 个字节)。字符串本身在内存中不必相邻,这样,如果您走过一个字符串的末尾,就会进入另一个字符串的开头。

IOW,你想象的 s 看起来像这样:

         +---+
s[0][0]: |'.'|
+---+
s[0][1]: |'-'|
+---+
s[0][2]: | 0 |
+---+
s[1][0]: |'-'|
+---+
s[1][1]: |'.'|
+---+
s[1][2]: |'.'|
+---+
...

事实并非如此。你实际上拥有的是这样的:

      +---+         +---+---+---+
s[0]: | | ------> |'.'|'-'| 0 | <-------------+
+---+ +---+---+---+ |
s[1]: | | ---+ |
+---+ | +---+---+---+---+---+ |
s[2]: | | -+ +--> |'-'|'.'|'.'|'.'| 0 | <-----+---- not guaranteed to be adjacent
+---+ | +---+---+---+---+---+ |
... | |
| +---+---+---+---+---+ |
+----> |'-'|'.'|'-'|'.'| 0 | <-----+
+---+---+---+---+---+

关于char** C 中的数组越界行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com