c - 通过指针的二维数组

标签 c pointers multidimensional-array

我想借助指针扫描二维数组并编写了这段代码,你能告诉我为什么编译器会出错吗?我知道如何使用双指针来做同样的事情,我正在试验这个。

#include<stdio.h>
#include<stdlib.h>
int main(void) {
    int i,j,n,a,b;
    int (*(*p)[])[];
    printf("\n\tEnter the size of the matrix in the form aXb\t\n");
    scanf("%dX%d",&a,&b);
    p=(int (*(*p)[b])[a])malloc(b*sizeof(int (*p)[a]));
    for(i=0;i<b;i++) {
            p[i]=(int (*p)[a])malloc(a*sizeof(int));
            printf("\t\bEnter Column %d\t\n");
            for(j=0;j<a;j++)
                    scanf("%d",&p[i][j]);
    }
    return 0;
}

最佳答案

你正在使用指向数组的指针,所以你不应该直接索引它们,因为 p[i] 会给出 *(p+i) 即一个数组如下p 指向的那个,而不是 p 的一个元素。

在 C 中,void* 将转换为任何指针类型,因此您无需强制转换 malloc 的结果。如果你确实放入了强制转换,它可以掩盖错误,例如,如果你试图分配给一个非指针(例如 p[i] )。

在 p 的 malloc 中,sizeof(int (*p)[a]) 应该使用类型或表达式,而不是声明。 p是一个指向int数组的指针数组的指针,所以*p的元素类型是int (*)[].

因此在 gcc 上编译时没有错误或警告:

#include<stdio.h>
#include<stdlib.h>
int main ( void )
{
    int i, j, n, a, b;

    int ( * ( * p ) [] ) [];

    printf ( "\n\tEnter the size of the matrix in the form aXb\t\n" );

    scanf ( "%dX%d", &a, &b );

    p = malloc ( b * sizeof ( int ( * ) [] ) );

    for ( i = 0;i < b;i++ ) {
        ( *p ) [i] = malloc ( a * sizeof ( int ) );
        printf ( "\t\bEnter Column %d\t\n", i );
        for ( j = 0;j < a;j++ )
            scanf ( "%d", & ( * ( *p ) [i] ) [j] );
    }


    return 0;
}

但是,由于使用指向数组的指针与使用指向其第一个元素的指针没有优势,但这确实意味着您必须在获取元素之前取消引用,因此使用指向指针形式的指针要容易得多.

关于c - 通过指针的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741000/

相关文章:

php - 通过另一个键和值在多维数组中查找值

javascript - 来自 Javascript 的 C 中的 Emscripten OOB 异常

c - 如何安全地将 void* 转换为 C 中的 int?

c - c中的转义序列

c - 在 C 中使用 typedef 函数指针

c - 警告 : passing argument 1 of ‘word_search’ from incompatible pointer type [enabled by default]

actionscript-3 - 如何遍历二维数组中的一圈值?

swift - 如何将数据保存到plist文件中的多维数组

c - 使用 GLEW 2.0 的 glewInit 段错误

c - 将结构体实例分配给 C 中的内部嵌套结构体