2

这是目前学习指南的一部分,虽然我意识到这不是很困难,但我无法理解它的要求。

编写一个函数: struct *grump(int i, int j) 它返回一个指向“struct grump”的指针,该指针在其字段 a,b 中保存值 i, j

所以我给了

struct grump
{
    int a;
    int b;
};

我只是对它的要求感到困惑

4

3 回答 3

3

它要求您分配struct grump将保存值的 aij,例如:

struct grump* func(int i, int j)
{
    struct grump *g = malloc(sizeof(*g));
    if (g != NULL) {
       g->a = i;
       g->b = j;
    }
    return g;
}

注意:我们在使用之前检查是否g != NULL成功malloc()grump如果没有,函数将返回NULL。当然在某些时候你会需要free()那个记忆,我相信你的学习指南很快就会提到它。

于 2012-11-19T07:10:45.170 回答
1

您必须编写一个函数,它将您传递给函数的值设置为,struct grump但这取决于您的结构对象在哪里。

如果它是全局的或者您正在使用分配,您可以访问 struct 对象malloc()

我已经展示了使用malloc()

你可以这样做:

struct grump* foo(int i, int j)
{
struct grump *ptg;
ptg=malloc(sizeof(struct grump));
if(ptg)
{
ptg->a=i;
ptg->b=j;
}
return ptg;
}

int main()
{
struct grump *pg;
pg=foo(5,10);
// Do whatever you want 
free(pg); // Don't forget to free , It's best practice to free malloced object
return 0;
}
于 2012-11-19T07:12:41.133 回答
1

C 中没有称为构造函数的内置东西,但这本质上就是您正在编写的内容。将它提升到一个新的水平并用于typedef创建一些稍微更像对象的结构可能是一个好主意。

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int a, b;
} g;

g *grump(int i, int j) {
  g *t = malloc(sizeof(g));
  t->a = i;
  t->b = j;
  return t;
}

int main(int ac, char **av) {
  g *a;

  a = grump(123, 456);
  printf("%d %d\n", a->a, a->b);
  return 0;
}
于 2012-11-19T07:18:45.777 回答