简体   繁体   English

了解C中的内存地址和指针

[英]Understanding memory addresses and pointers in C

I received the following question on one of my practice problemswhere it says to determine what is printed by this code: 我收到了关于我的一个练习问题的以下问题:它确定了由此代码打印的内容:

#include <stdio.h>
int main(){
    int ids[3] = {100,200,300};
    int *salary, salary1, salary2, *salary3;
    salary1 = ids[0] * ids[1];
    salary = &ids[1] ;
    salary2 = *(ids+1)* *(ids+2);
    salary3 = ids+2;
    printf("*salary = %d\nsalary1 = %d\n", *salary, salary1);
    printf("salary2 = %d\nsalary3 = %p\n", salary2, salary3);
}

I am a bit confused about this code. 我对这段代码感到有点困惑。 Firstly, in line 4: 首先,在第4行:

    int *salary, salary1, salary2, *salary3;

Why is there an asterisk at the beginning of salary3 if an asterisk was already used in the beginning of the line? 如果在行的开头已使用星号,为什么在salary3的开头有一个星号?

Secondly when it says: 其次说:

    salary1 = ids[0] * ids[1];

how are we supposed to determine the value of salary1 when we don't know the value of ids[1] ? 当我们不知道ids[1]的价值时,我们如何确定salary1 ids[1]的价值?

why is there an asterisk at the beginning of salary3 if an asterisk was already used in the beginning of the line? 如果在行的开头已经使用了星号,为什么在salary3的开头有一个星号?

The asterisk means the next variable is a pointer. 星号表示下一个变量是指针。 It's the same as: 它与以下相同:

int *salary;
int salary1;
int salary2;
int *salary3;

but on one line. 但在一条线上。

how are we supposed to determine the value of salary1 when we don't know the value of ids[1]? 当我们不知道ids [1]的价值时,我们如何确定薪水1的价值?

But you do know the value of ids[1]. 但你确实知道ids的价值[1]。 It's 200. 这是200。

Firstly, C declaration syntax is a bit confusing 首先,C声明语法有点令人困惑

int *x, y;

Means x is a pointer to an int, y is an int. 手段x是指向int的指针,y是int。 That's such a source of confusion that virtually every style guide forbids it. 这是一个混乱的源头,几乎每个风格指南都禁止它。

This 这个

  int ids[3] = {100,200,300};

declares an array. 声明一个数组。 ids[0] = 100, ids[1] = 200, ids[2] = 300. It's only really possible to match subscripts to array contents by eye when arrays are small. ids [0] = 100,ids [1] = 200,ids [2] = 300.当数组较小时,只能通过眼睛匹配下标数组内容。 So this isn't a normal use of arrays. 所以这不是数组的正常使用。 Either you have large read-only tables in global memory, or you create an array at runtime and fill it. 要么在全局内存中有大型只读表,要么在运行时创建一个数组并填充它。 However there shouldn't be an issue is ids[1] holding 200, that's how C array syntax works. 然而,应该没有问题是ids [1]持有200,这就是C数组语法的工作方式。

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

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