函数如何创建结构?

How can a function create a struct?

我在 C 编程课程中的一项作业是定义一个名为 create_card 的函数。此函数接收花色和卡值,以及 returns 一个 card_t 结构。

问题:函数应该如何创建结构?它不能只为结构创建值吗?是我误解了题目的意思还是作业写错了?

这是一个函数返回结构的例子。

struct test {
    int a;
};
struct test Fun(int k) {
    struct test d;
    d.a=k;
    return d;
}

struct test 替换为您的结构名称,将 struct test 的定义替换为您的结构定义。

如何使用

int main() {
    struct test Test=Fun(6);
    printf("%d",Test.a); // prints '6'
    return 0;
}

您可以 return 一个 struct 来自像 , or you can create a struct in C dynamic memory 中的函数(a.k.a。堆),使用 malloc 和 return 指向它的指针,例如

struct foo_st {
  int num;
  const char* str;
};

struct foo_st* 
/* the second argument s should practically be a literal string */
make_foo (int n, const char* s) {
   struct foo_st* p = malloc(sizeof(struct foo_st));
   if (!p) { perror("malloc foo"); exit(EXIT_FAILURE); };
   p->num = n;
   p->str = s;
   return p;
}

您的 main(或其他函数)稍后可能会执行 struct foo_st*fooptr = make_foo(32, "abc");,但应该有人调用 free(fooptr)(或至少 free 已在内部的地址fooptr).

当然,你永远不应该忘记 free 一个 malloc-ed 指针,当它变得无用时。害怕memory leaks, buffer overflow and undefined behavior. Read more about malloc(3) & free.

顺便说一句,实际上你应该决定谁负责 free-ing 内存。在上面的 make_foo 示例中,make_foo 的第二个参数应该是文字字符串(如果它是 malloc-ed,例如使用 strdup(3),您需要free 它在别处,那变得很乱)。

在实践中,您应该记录关于谁负责free的约定,之前一些动态malloc吃了记忆。您可能想使用 valgrind (if your system has it), and, if using a recent GCC compiler, its -fsanitize=address option to hunt memory related bugs. Very often, you happen to code both making and destroying functions (like here or here).

您可能想阅读有关 garbage collection (at least, to understand the concepts, such as reference counting, and the terminology). Perhaps you'll later want to use Boehm's conservative garbage collector 的内容。