简体   繁体   English

我这两个程序看起来一样,但其中一个导致错误

[英]my these two programs are looking same but one of these is causing error

here are my two programs and have a small difference.这是我的两个程序,有一点不同。 the first program compiles without error but the second program is giving error [enter image description here][1]第一个程序编译没有错误,但第二个程序出现错误[在此处输入图像描述][1]

Program 1:方案一:

#include<stdio.h>
int 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("%u %u\n", p, q);
    p++;
    q++;
    printf("%u %u\n", p, q);
    return 0;
}

this program compiles without any errors这个程序编译没有任何错误

Program 2:方案二:

#include<stdio.h>
int 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("%u %u\n",p,q);

    p++;
    q++;

    printf("%u %u\n",p,q);
    return 0;
}

program 2 shows error in the line 8 and 13 WHY?程序 2 在第 8 行和第 13 行显示错误,为什么?

The difference in the programs are int (*q)[4];程序的区别在于int (*q)[4]; versus int *q[4];int *q[4];

So let's see what https://cdecl.org/ says about the types.因此,让我们看看https://cdecl.org/关于这些类型的说明。

First code example第一个代码示例

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

declare q as pointer to array 4 of int将 q 声明为指向int 数组 4 的指针

So here q is a pointer and therefore you can assign to it - like q=a;所以这里q是一个指针,因此你可以分配给它 - 比如q=a;

Second code example第二个代码示例

int *q[4]; int *q[4];

declare q as array 4 of pointer to int将 q 声明指向 int 的指针的数组4

So here q is an array and therefore you can not assign to it, ie q=a;所以这里q是一个数组,因此你不能分配给它,即q=a; is illegal.是非法的。

For the second code example gcc gives the error:对于第二个代码示例,gcc 给出了错误:

error: assignment to expression with array type
     q=a;
      ^

which actually says the same, ie that you are assigning to something being an array (and that is an error, ie illegal).它实际上说的是相同的,即您正在分配一个数组(这是一个错误,即非法)。

It is because arrays are not assignable.这是因为数组不可分配。 q in the second program is defined as an array of pointers, so when you do: q = a; q在第二个程序中被定义为一个指针数组,所以当你这样做时: q = a; , this is not valid in C. Likewise, when you write q++ , this is equivalent to q = q + 1; , 这在 C 中是无效的。同样,当你写q++ ,这等价于q = q + 1; , so same kind of error. ,所以同样的错误。

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

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