为什么我的文件2中没有访问文件1中的静态全局指针 [英] Why is my global pointer to a static in file 1 is not being accessed in my file 2

查看:60
本文介绍了为什么我的文件2中没有访问文件1中的静态全局指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我创建了两个文件。我知道静态变量只有文件范围。所以,在这里我试图获取一个全局指针并指向该静态变量,并希望通过我的另一个文件中的指针使用该静态变量的值。但我无法做到。请纠正我!



文件1.c:

Guys, I created two files. I know that a static variable has just file scope. So, here I am trying to take a global pointer and pointing to that static variable and want to use that static variable's value through pointer in my other file. But I am unable to do it. Please correct me!

File 1.c:

#include <stdio.h>
static int name;
int *p=&name;
int main()
{
    extern name;
    name = 20;
    extern *p;
    printf("add of p is %p and value odf p is %d\n",p,*p);
    return 0;
}





文件2.c:



File 2.c:

#include <stdio.h>
void strlength(void)
{
    extern int *p;
    printf("value of name from 1.c is: %d\n",*p);
}





输出:

加p为0x804a028,p值为20



Output:
add of p is 0x804a028 and value of p is 20

推荐答案

试试这个

Try this
// file 1.c
#include <stdlib.h>
#include <stdio.h>

static int name;
extern int *p=&name;
int main()
{
    extern void strlength();
    name = 20;
    printf("add of p is %p and value odf p is %d\n",p,*p);
    strlength();
    
    getchar();
    return 0;
}
</stdio.h></stdlib.h>







// file 2.c
#include <stdlib.h>
#include <stdio.h>

void strlength(void)
{
    extern int *p;
    printf("value of name from 1.c is: %d\n",*p);
}
</stdio.h></stdlib.h>


这样就行了

This way it would work
#include <stdio.h>
static int name;
int *p=&name;
void strlength(void);
int main()
{
  name = 20;
  printf("add of p is %p and value odf p is %d\n",p,*p);

  strlength();

  return 0;
}



然而,这是错误代码的一个很好的例子。


However that's a good example of bad code.


这篇关于为什么我的文件2中没有访问文件1中的静态全局指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆