我已经检查了谷歌一个小时。我曾尝试使用 typdef,但我得到了相同的结果。我对结构范围有些困惑。我敢肯定,我错过了一些愚蠢的事情。
示例,打印 0:
#include <stdio.h>
struct info
{
int i;
};
struct info testinfo;
int test()
{
testinfo.i = 5;
}
int main()
{
printf("%d", testinfo.i);
}
我已经检查了谷歌一个小时。我曾尝试使用 typdef,但我得到了相同的结果。我对结构范围有些困惑。我敢肯定,我错过了一些愚蠢的事情。
示例,打印 0:
#include <stdio.h>
struct info
{
int i;
};
struct info testinfo;
int test()
{
testinfo.i = 5;
}
int main()
{
printf("%d", testinfo.i);
}
两个 struct info 都具有块范围,因为您将它们声明为局部变量。因此它们是不同的对象。在文件范围内仅声明一个(在任何函数之外)。
(有问题的代码已经过编辑,这个答案是指最初的错误)。
这与 struct 无关 - 您会看到任何类型的相同行为。发生的事情是每个testinfo
都在不同的范围和命名空间中。
此外,您永远不会调用您的函数。
您可以将其设为testinfo
全局,也可以通过指针传递它,这是一个更好的主意:
#include <stdio.h>
struct info
{
char* buf;
};
int test(struct info* testinfo)
{
testinfo->buf = "test"; // it's a bad idea to have a char* to a literal
// you should probably allocate new storage
}
int main()
{
struct info testinfo;
test(&testinfo);
printf("%s", testinfo.buf);
}
您将需要将变量传递testinfo
给函数test()
或test()
返回一个info
结构
这是第一个选项:
int test(struct info * ti) {
ti->buf = "test";
}
int main() {
struct info testinfo;
test(&testinfo);
printf("%s", testinfo.buf);
}
注意:*
表示指向结构的指针,否则您将复制结构并且对它的任何修改只会发生在副本中(因此main
' 的版本不会改变)
当你这样做
printf("%s", testinfo.buf);
testinfo.buf 没有分配!尝试
struct info testinfo;
testinfo.buf = (char *) malloc(123);
<编辑>
strcpy(testinfo.buf, "hello world!");
</编辑>
printf("%s", testinfo.buf);
获得分配的缓冲区。
你不能做一个
testinfo.buf = "test"
struct info
{
char buf[10]; /*10 is the space for buf*/
};
您也应该strcpy(dest,source)
在分配字符串时使用。而且你也没有打电话给测试。把这两件事整理出来,你就会得到输出。
约翰,您需要test
在printf
.
IE
int main()
{
test();
printf("%d", testinfo.i);
return(0);
}