简体   繁体   English

数组指针赋值给二维数组

[英]Array pointers assignmnet to 2-D array

void  main()
  {
    int a[][4]={ 5,7,5,9,
                 4,6,3,1,
                 2,9,0,6};
    int *p;
    int *q [4];
    p=(int *)a;
    q=a;
    printf("\n %u %u",p,q);
    p++;
    q++;
    printf("\n %u %u",p,q);
}

My query is can we assign 2-D array to the array of pointers.我的查询是我们可以将二维数组分配给指针数组。 The above code shows error as 1.c: In function 'main': 1.c:14:6: error: assignment to expression with array type上面的代码显示错误为1.c: In function 'main': 1.c:14:6: error: assignment to expression with array type

In C language, arrays are not first class citizens:在 C 语言中,数组不是一等公民:

  • an array decays to a pointer when it is used in an expression数组在表达式中使用时衰减为指针
  • you can never assign to an array你永远不能分配给一个数组

If q is an array of pointer, the answer is no, you cannot assign to an array.如果q是一个指针数组,答案是否定的,你不能赋值给一个数组。

If you want q to be a pointer to arrays , you must declare it as int (*q)[4];如果您希望q成为指向数组指针,则必须将其声明为int (*q)[4]; :

int(*q)[4];
q = a;

You can then use it to access elements of a : q[i][j] is the same as a[i][j] (and q[i] the same as q[j] )然后,可以用它来的存取元件aq[i][j]是相同的a[i][j]q[i]相同, q[j]

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

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