c - 地址重合(指针,C 编程)

标签 c pointers

我有两个二维数组,但我不知道为什么或如何使每个数组中的两个元素的地址重合。 这是源代码:

#include <stdio.h>

int main()
{
    int i,j,m,n,o,p,*ptr;
    printf("Enter dimension of 1st matrix: ");
    scanf("%d * %d",&m,&n);
    printf("Enter dimension of 2nd matrix: ");
    scanf("%d * %d",&o,&p);
    int *a[m][n];
    int *b[o][p];
    if (n!=o) return 0;

    printf("\nEnter 1st matrix:\n");
    for (i=0;i<m;i++)
        for (j=0;j<n;j++)
        {   printf("%d   ",(a+i*(n-1)+i+j)); scanf("%d",(a+i*(n-1)+i+j));   }

    printf("\nEnter 2nd matrix:\n");
    for (i=0;i<o;i++)
        for (j=0;j<p;j++)
        {   printf("%d   ",(b+i*(p-1)+i+j)); scanf("%d",(b+i*(p-1)+i+j));   }

    /*Printing the matrices*/
    puts("");puts("");
    for (i=0;i<m;i++)
        {for (j=0;j<n;j++)
            {   ptr = (a+i*(n-1)+i+j);
                printf(" %d ",*ptr);    }   puts("");}puts("");
    for (i=0;i<o;i++)
        {for (j=0;j<p;j++)
            {   ptr = (b+i*(p-1)+i+j);
                printf(" %d ",*ptr);    }   puts("");}
}

这是一个打印屏幕; Screen print showing two coinciding adresses

因此,我在计算两个矩阵乘积的简单程序中遇到错误。问题是,这正常吗?编译器或操作系统不应该处理这个问题吗?

此外,为什么我必须执行 ptr = (a+i*(n-1)+i+j); printf("%d ",*ptr);?
为什么 printf("%d ",*(a+i*(n-1)+i+j)); 不起作用?

最佳答案

首先,ab 是指针数组,指针永远不会被初始化。

int *a[m][n];
int *b[o][p];

我猜它的意思是:

int a[m][n];
int b[o][p];

(其余代码需要相应更改。)

其次,您将指针视为 int(例如在 %d 中)。请记住,指针可以比 int 更宽。例如,在我的平台上,指针是 64 位的,ints 是 32 位的。

关于c - 地址重合(指针,C 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8808707/

相关文章:

c - scanf 将数组传递给函数后出现段错误

c - 尝试将值复制到指针 str 时获取 null

c++ - 性能问题 : Inverting an array of pointers in-place vs array of values

c - 从 char 指针检索最后一组输入值

c - 在释放指针变量指向的内容后重用它们是否安全?

将BMP转换为灰度图

检查指针是否已分配

c - OS X 10.9.2 上 Eclipse 4.3.0 中 C 的 "Launch failed. Binary not found"错误

java - 我的国际象棋程序的线程 "main"java.lang.NullPointerException 中出现异常

C++ unique_ptr 常量引用