C - 在多个函数中使用结构

时间:2012-06-07 20:19:52

标签: c data-structures

我一直在检查谷歌一个小时。我尝试过使用typdef但是得到了相同的结果。我对结构范围有点困惑。我确定这是一件我很遗憾的事情。

示例,打印0:

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

int test()
{

    testinfo.i = 5;
}

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

6 个答案:

答案 0 :(得分:7)

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

(有问题的代码已被编辑,此答案涉及最初的错误)。

答案 1 :(得分: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);
}

答案 2 :(得分: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的版本不会改变)

答案 3 :(得分:0)

当你这样做时

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

testinfo.buf未分配!试试

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

&LT;编辑&gt;

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

&LT; /编辑&gt;

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

获取缓冲区。

答案 4 :(得分:0)

你无法做到

testinfo.buf = "test"
  1. 你必须为字符串分配空间,buf只是一个字符指针。
  2. struct info { char buf[10]; /*10 is the space for buf*/ };

    在分配字符串时也应该使用strcpy(dest,source)。 而且你也没有打电话给考试。 对这两件事情进行排序,你会得到输出。

答案 5 :(得分:0)

John,您需要在test之前致电printf更新问题。

int main()
{
  test();
  printf("%d", testinfo.i);
  return(0);
}