gpt4 book ai didi

c - 理解指针和内存地址

转载 作者:行者123 更新时间:2023-12-03 23:27:35 25 4
gpt4 key购买 nike

#include<stdio.h>

int g(int *a, int *b);

int main()
{
int a = 2;
int b = 7;

b = g(&b , &a);

printf("a = %d\n", a);
printf("b = %d\n", b);

return 0;
}

int g(int *a, int *b)
{
(*a) = (*a) + 3;
(*b) = 2*(*a) - (*b)+5;

printf("a = %d, b = %d\n", *a, *b);

return (*a)+(*b);
}

输出是:
a = 10, b = 23
a = 23
b = 33

我正在学习 C 编程入门类(class),但无法理解这是如何工作的。

谢谢您的帮助!

最佳答案

对有问题的事件进行排序:

int main()
{

Declaration of a and b and value assignment:

    int a = 2;
int b = 7;


Here is a trick, the address passed to the parameter int* a is actually of b, and vice-versa on the second parameter:

    b = g(&b , &a);


Here just printing values of a and b:

    printf("a = %d\n", a);
printf("b = %d\n", b);

return 0;
}


Since the parameters are pointers, the changes made, in the scope of this function, to the variable addresses pointed by them are permanent:

int g(int *a, int *b) {


Here, dereferencing the pointer (*a, the parentheses are not needed in these cases), means you are now working with the value stored in the address pointed by a, so 7 + 3 = 10, now the value stored in the address pointed by a is = 10:

    (*a) = (*a) + 3;


Here, the same thing, dereferencing pointers, so 2 * 10 - 2 + 5 = 23, the value stored in the address pointed by b will be 23:

    (*b) = 2*(*a) - (*b)+5;


Here printing a = 10 and b = 23, again, dereferencing pointers means you are working with the values stored in the addresses pointed by them:

    printf("a = %d, b = %d\n", *a, *b);


The returned value is 10 + 23 = 33, so for b = g(&b, &a), b will be assigned the value of 33, a is already 23 so it stays that way:

    return (*a)+(*b); 
}

关于c - 理解指针和内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60802403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com