search

Home  >  Q&A  >  body text

c++ - 数组地址问题

int a[3] = {0,1,2};

数组a和a[0]的地址是一样的. 但是不同在哪儿呢?用它们的地址进行运算的时候不太一样
那请问, 这样理解对吗?
比如规定数国家省份的时候从西向东数
那新疆是中国的第一个省份, 中国的地址和中国[0](新疆)的地址是一样的。但是用来计算的时候,
中国++; //就变成了朝鲜, 加一变成了跨国家
&中国[0]++; //就变成了青海, 加一只是跨城市

这样理解正确吗?

大家讲道理大家讲道理2773 days ago426

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:21:53

    The value of the

    address is the same, but the two data types are different. The type of &a[0] is int*, while the type of &a is int (*)[3].

    Add the array name a. The array name is a pointer to the first element of the array, so in your example, a and &a[0] are strictly equal (same type, same value), but when For high-dimensional arrays, you need to identify which first element is, for example: {{1, 2, 3}, {4, 5, 6}}, which is the first element? 1 or {1, 2, 3}?

    reply
    0
  • 阿神

    阿神2017-04-17 14:21:53

    Suggest my answer

    Post the results of my local machine

    #include <stdio.h>
    
    int main() {
        int a[3] = {0, 1, 2};
    
        printf("%p,%p\n", a, &a[0]); 
        printf("%p,%p\n",a+1,&a[0]+1); // 为什么不用,稍后说明
    
        return 0;
    }
    0x7fff5af6e32c,0x7fff5af6e32c
    0x7fff5af6e330,0x7fff5af6e330
    

    The conclusion is a+1, &a[0]+1, the results are consistent
    So why not use a++?

    Variables in C can perform ++ operations
    But here an array is declared and memory is allocated. int a[3] = {0, 1, 2};
    a is already a constant, so it cannot Perform a++ operation

    As for the data types mentioned by @leunggamciu are different
    This happens in multi-dimensional arrays
    int b2, then b +1 actually needs to add +3 int types, &b +1, just add + 1 int type length

    But in one-dimensional array, it is the same, there is no difference

    I have just learned C language. If there is anything wrong, please point it out, thank you

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:21:53

    The address of your array is already a constant, so you cannot use the increment or decrement operator. If the increment operator is applied to the lvalue
    question, the syntax is wrong.
    I agree with @leunggamciu’s statement, the type has changed, I borrowed @dryyun’s code

    #include <stdio.h>
    
    int main() {
        int a[3] = {0, 1, 2};
    
        printf("%p,%p\n", a, &a[0]); 
        printf("%p,%p\n",&a+1,&a[0]+1); // 这里的 a在+1前 取地址,
    
        return 0;
    }
    
    题主运行下看看结果吧

    reply
    0
  • Cancelreply