C的全球指针

发布于 2025-01-30 19:20:45 字数 274 浏览 2 评论 0原文

我想知道我如何得到答案 以下代码可以用任何人解释..

用C语言。.

#include <stdio.h>

int*p;
void fun(int a, int b)
{
    int c;
    c = a+b ;
    p=&c;
}
int main()
{
    fun(2,3);
    printf("%d",*p);
    return 0;
}

如果指示在全球范围内声明了指针,如何访问返回主函数后折叠的内存

I want to know how I am getting answer for
the below code can anyone pls explain ..

In c language..

#include <stdio.h>

int*p;
void fun(int a, int b)
{
    int c;
    c = a+b ;
    p=&c;
}
int main()
{
    fun(2,3);
    printf("%d",*p);
    return 0;
}

If the pointer is declared globally how it's possible to access the memory that was collapsed after return to the main function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百变从容 2025-02-06 19:20:45

函数到期后,您没有本地变量c。因此,指针p指向什么?您的代码具有不可预测的行为。
该解决方案是分配一些内存,并将其分配给p。请注意,在使用p结束时释放分配的内存是一种最佳实践。

#include <stdio.h>
#include <stdlib.h>

int* p;

void fun(int a, int b) {
    int* c = malloc(sizeof(int));
    *c = a + b;
    p = c;
}

int main() {
    fun(2, 3);
    printf("%d", *p);
    free(p);
    return 0;
}

You don't have the local variable c after the expiration of the function. So the pointer p is pointing to what? Your code has unpredictable behavior.
The solution is allocating some memory and assigning it to p. note that it is a best practice to free the allocated memory at the end of using p.

#include <stdio.h>
#include <stdlib.h>

int* p;

void fun(int a, int b) {
    int* c = malloc(sizeof(int));
    *c = a + b;
    p = c;
}

int main() {
    fun(2, 3);
    printf("%d", *p);
    free(p);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文