简体   繁体   English

二维阵列存储器映射C.

[英]2D Array Memory Mapping C

I have a 2d array and a pointer which points to its first element: 我有一个2d数组和一个指向其第一个元素的指针:

int s[100][100];
int* p; 

after reading some value and saving in s: 读完一些值并保存在s中:

p=&s[0][0]

Well, now I want to print s elements, by accessing it through p: 好吧,现在我想打印s元素,通过p访问它:

for (x = 0; x<m; x++)
{
    for (y = 0; y<n; y++)
    {
        printf("%d ", *(p + sizeof(int)*x*n + y));
    }
    printf("\n");
}

which m is the number of rows and n is the number of columns. m是行数,n是列数。 But... It gives me wrong answer. 但是......它给了我错误的答案。 I guess the expression 'p + sizeof(int)*x*n + y' is causing the problem. 我猜表达式'p + sizeof(int)* x * n + y'导致问题。 Please help me correct it. 请帮我纠正一下。 Thanks. 谢谢。

You don't need the sizeof(int) - pointer arithmetic takes care of element size automatically - change: 你不需要sizeof(int) - 指针算法自动处理元素大小 - 更改:

p + sizeof(int)*x*n + y

to: 至:

p + x*n + y

There are couple of errors. 有几个错误。 The first one was pointed out by Paul K. The second one is that you will have to use: Paul K指出了第一个。第二个是你必须使用:

    printf("%d ", *(p + x*100 + y));

instead of 代替

    printf("%d ", *(p + x*n + y));

Otherwise, you will be picking up the numbers from the wrong row. 否则,您将从错误的行中获取数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM