c - 确定内存中指针的字节数

标签 c arrays pointers

我对递增数组指针然后测量指针位置的字节差异感到困惑。

我知道指针 *p 在移动多维数组时会增加数据类型的大小。然而,当一个数组时,thisArray被使用:

int thisArray[ 7 ][ 4 ];

应该如何评估thisArrray + 1?我是否同时增加行和列?

我想知道这些指针将在内存中相隔多少字节。

我知道确切的答案将取决于平台。我在寻求解决的方法,而不是确切的答案。

因为我不能在注释中格式化代码:我把它放在这里:

//使用 sizeof

#include <stdio.h>

int main(void) {

int tbl[ 7 ][ 4 ];

// Size of tbl
int x = sizeof(*tbl);
printf ( "%d\n" , x);

// Size of tbl + 1;
int y = sizeof(*tbl+1);
printf( "%d\n", y);

//Size apart in bytes
int z = y - x;
printf("%d\n", z);

return 0;
}

最佳答案

how should thisArrray + 1 be evaluated?

thisArray 衰减为指针时,指针类型为int (*)[4]thisArray+1的类型相同。

Do I increment both rows and columns?

是的。

如果使用行和列结构查看 thisArray 的内存,您有:

thisArray ->       +----+----+----+----+
                   |    |    |    |    |
thisArray + 1 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 2 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 3 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 4 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 5 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 6 ->   +----+----+----+----+
                   |    |    |    |    |
thisArray + 7 ->   +----+----+----+----+

如果要遍历数组的元素,可以使用索引或指针。

使用索引遍历:

for ( int i = 0; i < 7; ++i )
{
   for ( int j = 0; j < 4; ++j )
   {
       // Use thisArray[i][j];
   }
}

使用指针遍历:

for ( int (*ptr1)[4] = thisArray; ptr1 < thisArray+7; ++ptr1 )
{
   for ( int* ptr2 = *ptr1; ptr2 < *ptr1 + 4; ++ptr2 )
   {
       // Use *ptr2
   }
}

从可读性的角度来看,使用索引遍历数组要直观得多。我强烈建议使用它。

关于c - 确定内存中指针的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39948888/

相关文章:

c - 正确释放结构

c++ - 什么时候应该在 C++ 中使用 new 关键字?

C++ 无效的指针值

c - 添加编译阶段

c - 处理 IRP_MJ_SHUTDOWN

javascript - 如何结束 .empty()

ios - 如何对字符串的日期进行排序?

无法在cgi中执行外部命令

c - c中结构指针之间的区别

java - 检查数组长度是否是完全平方数