-2

我已经检查了谷歌一个小时。我曾尝试使用 typdef,但我得到了相同的结果。我对结构范围有些困惑。我敢肯定,我错过了一些愚蠢的事情。

示例,打印 0:

#include <stdio.h>
struct info
{
    int i;
};
struct info testinfo;

int test()
{

    testinfo.i = 5;
}

int main()
{
    printf("%d", testinfo.i);
}
4

6 回答 6

7

两个 struct info 都具有块范围,因为您将它们声明为局部变量。因此它们是不同的对象。在文件范围内仅声明一个(在任何函数之外)。

(有问题的代码已经过编辑,这个答案是指最初的错误)。

于 2012-06-07T20:23:08.913 回答
3

这与 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);
}
于 2012-06-07T20:24:15.557 回答
2

您将需要将变量传递testinfo给函数test()test()返回一个info结构

这是第一个选项:

int test(struct info * ti) {
  ti->buf = "test";
}
int main() {
  struct info testinfo;
  test(&testinfo);
  printf("%s", testinfo.buf);
}

注意*表示指向结构的指针,否则您将复制结构并且对它的任何修改只会发生在副本中(因此main' 的版本不会改变)

于 2012-06-07T20:23:53.270 回答
0

当你这样做

printf("%s", testinfo.buf);

testinfo.buf 没有分配!尝试

struct info testinfo;
testinfo.buf = (char *) malloc(123);

<编辑>

strcpy(testinfo.buf, "hello world!");

</编辑>

printf("%s", testinfo.buf);

获得分配的缓冲区。

于 2012-06-07T20:23:56.523 回答
0

你不能做一个

testinfo.buf = "test"
  1. 您必须为字符串分配空间, buf 只是一个字符指针。

struct info { char buf[10]; /*10 is the space for buf*/ };

您也应该strcpy(dest,source)在分配字符串时使用。而且你也没有打电话给测试。把这两件事整理出来,你就会得到输出。

于 2012-06-07T20:26:49.143 回答
0

约翰,您需要testprintf.

IE

int main()
{
  test();
  printf("%d", testinfo.i);
  return(0);
} 
于 2012-06-07T20:28:09.907 回答