通过指针的二维数组

发布于 2024-09-19 19:08:29 字数 603 浏览 1 评论 0原文

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

#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;
}

I want to scan a 2D array with the help of pointers and have written this code, could you tell me why the compiler gives errors? I know how to use double pointers to do the same, i was experimenting with this one.

#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;
}

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

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

发布评论

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

评论(3

怪我鬧 2024-09-26 19:08:29

您正在使用指向数组的指针,因此您不应该直接对它们进行索引,因为 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;
}

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

You are using pointers to arrays, so you shouldn't index them directly, as p[i] will give *(p+i) i.e. an array following the one pointed to by p, rather than an element of p.

In C, void* will convert to any pointer type, so you don't need to cast the result of malloc. If you do put the casts in, it can mask errors, for example if you are trying to assign to a non-pointer ( such as p[i] ).

In the malloc for p, sizeof(int (*p)[a]) should either use a type or an expression, not a declaration. p is a pointer to an array of pointers to arrays of int, so the type of the elements of *p is int (*)[].

So this compiles without error or warning on 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;
}

However, since there is no advantage in using a pointer to an array against using a pointer to its first element but it does mean you have to dereference before taking the element, it is much easier to use the pointer to a pointer form.

绝不放开 2024-09-26 19:08:29

你知道int (*(*p)[])[]是什么吗?
尝试 cdecl.org ... http://cdecl.ridiculousfish.com/?q=int+%28%2A%28%2Ap%29%5B%5D%29%5B%5D

使用一维数组并假装它是一个二维对象

  1. 声明一个一维对象(指针、数组等)
  2. malloc 一个矩形大小
  3. 根据行、列和列大小计算线性寻址值
  4. 使用它
  5. free 数组

就是这样

/* Oh ... and use spaces in your code */
/* They are extremely cheap now a days */
#include <assert.h>
/* instead of asserting malloc and scanf, use proper error checking */
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i, j, n, rows, cols;
    int *p;                                            /* 1. */

    printf("Enter the size of the matrix in the form aXb\n");
    n = scanf("%dX%d", &rows, &cols);
    assert((n == 2) && ("scanf failed"));
    p = malloc(rows * cols * sizeof *p);               /* 2. */
    assert((p != NULL) && "malloc failed");
    for (i = 0; i < rows; i++) {
            int rowindex = i * cols;                   /* 3. */
            for (j = 0; j < cols; j++) {
                    n = scanf("%d", &p[rowindex + j]); /* 3. and 4. */
                    assert((n == 1) && "scanf failed");
            }
    }
    free(p);                                           /* 5. */
    return 0;
}

Do you know what int (*(*p)[])[] is?
Try cdecl.org ... http://cdecl.ridiculousfish.com/?q=int+%28%2A%28%2Ap%29%5B%5D%29%5B%5D

To use a 1-dimensional array and pretend it's a 2-dimensional one

  1. declare a 1-dimensional object (pointer, array, whatever)
  2. malloc a rectangular size
  3. compute linear addressing value based on row, column, and column size
  4. use it
  5. free the array

That's it

/* Oh ... and use spaces in your code */
/* They are extremely cheap now a days */
#include <assert.h>
/* instead of asserting malloc and scanf, use proper error checking */
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i, j, n, rows, cols;
    int *p;                                            /* 1. */

    printf("Enter the size of the matrix in the form aXb\n");
    n = scanf("%dX%d", &rows, &cols);
    assert((n == 2) && ("scanf failed"));
    p = malloc(rows * cols * sizeof *p);               /* 2. */
    assert((p != NULL) && "malloc failed");
    for (i = 0; i < rows; i++) {
            int rowindex = i * cols;                   /* 3. */
            for (j = 0; j < cols; j++) {
                    n = scanf("%d", &p[rowindex + j]); /* 3. and 4. */
                    assert((n == 1) && "scanf failed");
            }
    }
    free(p);                                           /* 5. */
    return 0;
}
浅唱々樱花落 2024-09-26 19:08:29

您不必要地使使用指针访问数组元素的问题变得复杂化。
尝试使用简单的指针到指针 p。

int **p;
...
p=malloc(a*sizeof(int *));   //create one pointer for each row of matrix
...
for(i=0;i<a;i++)
{
...
p[i]=malloc(b*sizeof(int));  //create b integers in each row of matrix
...
}

You are unnecessarily complicating the problem of accessing array elements using pointers.
Try to use a simple pointer-to-pointer p.

int **p;
...
p=malloc(a*sizeof(int *));   //create one pointer for each row of matrix
...
for(i=0;i<a;i++)
{
...
p[i]=malloc(b*sizeof(int));  //create b integers in each row of matrix
...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文