插入到c中的动态二维数组

发布于 2024-12-18 08:52:30 字数 1135 浏览 4 评论 0原文

我试图将一个值插入到动态二维字符数组中:

    theBoard->_board[row][col] = val;

但是在每次将字符分配给(行,列)时,它也会将其放在(行1,列+8)上。 可能是什么问题?

这是数组的分配:

    if ((new = (BoardP) malloc(sizeof(struct Board))) == NULL)
{
    reportError(MEM_OUT);
    return NULL;
}
if ((new->_board = (char**) malloc(rows * sizeof(char*))) == NULL)
{
    reportError(MEM_OUT);
    return NULL;
}
int i,j;
for (i=0;i<rows;i++)
{
    if ((new->_board[i] = (char*) malloc(cols * sizeof(char))) == NULL)
    {
        reportError(MEM_OUT);
        return NULL;
    }

当我插入“X”并打印时:

BoardP b = createNewDefaultBoard();
b->_board[2][0] = 'X';
printBoard(b,0,0);

我得到以下输出:

     0  1  2  3  4  5  6  7  8  9
0                                
1                            X   
2    X                           
3                                
4                                
5                                
6                                
7                                
8                                
9                                

im trying to insert a value to a dynamic 2d array of chars:

    theBoard->_board[row][col] = val;

but on each assignment of a char to (row,col), it also puts it on (row-1,col+8).
what could be the problem?

here's the allocation of the array:

    if ((new = (BoardP) malloc(sizeof(struct Board))) == NULL)
{
    reportError(MEM_OUT);
    return NULL;
}
if ((new->_board = (char**) malloc(rows * sizeof(char*))) == NULL)
{
    reportError(MEM_OUT);
    return NULL;
}
int i,j;
for (i=0;i<rows;i++)
{
    if ((new->_board[i] = (char*) malloc(cols * sizeof(char))) == NULL)
    {
        reportError(MEM_OUT);
        return NULL;
    }

when i'm inserting an 'X' and printing with:

BoardP b = createNewDefaultBoard();
b->_board[2][0] = 'X';
printBoard(b,0,0);

i'm getting this output:

     0  1  2  3  4  5  6  7  8  9
0                                
1                            X   
2    X                           
3                                
4                                
5                                
6                                
7                                
8                                
9                                

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离不开的别离 2024-12-25 08:52:30

您的看板可能只有 8 列。如果您访问第 8 列以上,您将读取(或写入)内存中的下一行,除了最后一行之外的所有内容都是下一行。

 <0,1> <0,2> <0,3> <0,4> <0,5> <0,6> <0,7>  --> 
 <1,0> <1,2> <1,3> <1,4> <1,5> <1,6> <1,7>  -->
 ...

Your board probably only has 8 columns. If you access column 8+ you will be reading (or writing) whatever is next in memory, which for all but the last row is the next row.

 <0,1> <0,2> <0,3> <0,4> <0,5> <0,6> <0,7>  --> 
 <1,0> <1,2> <1,3> <1,4> <1,5> <1,6> <1,7>  -->
 ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文