0

鉴于以下代码,我在运行时收到以下错误

致命的运行时错误:第 21 行,第 11 列,线程 id 0x00002068:
越界指针的取消引用:超过数组末尾的 1 个字节(1 个元素)。

我在这里做错了什么?我创建了一个 2D 字符数组并将所有元素初始化为“x”。然后我尝试使用指针逻辑打印所有元素。它将字符打印到标准 IO,但随后引发运行时错误。我没有看到越界发生在哪里。

#include <stdio.h>
#define EDGE 10

int main(void){

    char fabric[EDGE][EDGE];
    char *cell = fabric;
    int totalCells = EDGE*EDGE;

    for(int i = 0; i < totalCells; ++i){    
            *(cell + i) = 'x';
    }

    cell = fabric; //set cell to point back to first element

    while(*cell){                  //while there is content at address, print content
        printf("%c", *cell);
        ++cell;
    }

    getchar();
    return 0;

}
4

2 回答 2

1

强烈建议您只 malloc/memset 您的结构,而不是做 hacky 指针的事情。

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

#define EDGE        ( 10 )
#define TOTAL_CELLS ( EDGE * EDGE )

int main()
{
    int i;
    char * fabric = malloc(TOTAL_CELLS);
    memset(fabric,'x',TOTAL_CELLS);


    for(i=0; i<TOTAL_CELLS; i++){
        printf("%c",fabric[i]);
    }

    return 0;
}

如果您仍想引用类似二维数组的结构fabric[i][j]fabric[i*EDGE+j]

于 2019-05-30T16:02:25.070 回答
0

首先数组不包含字符串。所以这个条件

while(*cell){ 

导致未定义的行为。

您还必须在声明和语句中转换指针

char *cell = ( char * )fabric;

cell = ( char * )fabric;

因为没有从 typechar ( * )[EDGE]到 type的隐式转换char *

于 2019-05-30T15:23:59.730 回答