处理堆栈变量的指针示例

Example of Pointers dealing with Stack variables

我在 Pointers 浏览了这一章并遇到了这句话:

You will use pointers to deal with variables that have been allocated on the heap. (You can use pointers to deal with stack variables, but in most cases this just isn't necessary).

我知道如何使用指针来处理已在堆上分配的变量。但我无法想象如何使用它来处理堆栈变量。由于函数退出时堆栈变量会自动释放(即变量被推出堆栈),如何在不使用 free 系统调用之类的情况下用指针完成同样的操作(如上面引用的文本所暗示的那样)?这可能吗?

您可以使用 address-of 运算符 & 获取局部变量(分配在堆栈上)的地址。然后可以将该地址存储在指针中,并像指向堆上的变量一样使用。但是,您应该 而不是 free() 存储的地址,因为这构成了未定义的行为。

简单示例:

int i;
scanf("%d", &i);

将指向堆栈变量 i 的指针传递给 scanf(),以便将结果存储在那里。

堆栈变量使用指针的常见示例:从另一个函数修改局部变量的值。

#include <stdio.h>

void hoge(int *a) {
    *a = *a + 10;
}

int main(void) {
    int foo = 5;
    printf("%d\n", foo);
    hoge(&foo);
    printf("%d\n", foo);
    return 0;
}

在函数内部,您可以使用指针算法并引用堆栈上的变量。 变量在函数开始时压入堆栈并在结束时弹出。

在此示例中,您可以通过 a 的地址访问 b(请记住压入堆栈的参数顺序 What is argument push order)。

void fnc(unsigned int a, unsigned int b) {
    unsigned int *pb = (unsigned int *)((long)&a - (long)sizeof(int));
    printf("%d\n", *pb);
}

交换两个变量值的一种非常流行和已知的方法是另一个例子。

#include <stdio.h>

void Swap(char *x,char *y);

int main(void)
{
    char character1 = 'a';

    char character2 = 'z';

    Swap(&character1,&character2);

    printf("character1 now is : %c\n",character1);

    printf("character2 now is : %c\n",character2);
}

void Swap(char *x,char *y)
{
    char tmp;

    tmp = *x;

    *x = *y;

    *y = tmp;
}