哪种约定在C编程中更好?

时间:2013-09-05 12:04:11

标签: c pointers struct

我的问题涉及C指针的主题。想象一下以下场景: 我有一个名为“stc”的结构变量定义如下:

struct stc {
       int data;
       char ch;
}

在我的程序中的Main()函数的开头声明。我想设置值 使用函数的结构中的字段(即 data )。

现在我的问题是以下哪个更好,为什么?

第1号惯例: 写一个函数返回一个类型为 stc 的指针:

struct stc *func(int d, char c)
{
    stc *tmp = malloc(sizeof(stc))
    tmp -> data = d;
    tmp -> ch = c;

    return tmp;
}

以及稍后在不再需要结构时释放已分配的内存。

约定2:编写一个接收结构指针的函数,并向其发送stc的地址

void func(stc *stcP, int d, char c)
{
     stcP -> data = d;
     stcP -> ch = c;
}

非常感谢!

3 个答案:

答案 0 :(得分:5)

第一次使用可能会导致内存泄漏而无需小心。

第二种用法更好,但你不正确地使用箭头操作符,它应该是:

void func(stc *stcP, int d, char c)
{
    stcP -> data = d;
    stcP -> ch = c;
}

答案 1 :(得分:4)

我有两种或各种变体:

typedef struct stc stc;


#define STC_INITIALIZER(D, C) { .data = d, .ch = c, }

stc* stc_init(stc *stcP, int d, char c) {
  if (stcP) {
     *stcP = (stc)STC_INITIALIZER(d, c);  // Initialize with a compound literal
  }
  return stcP;
}

stc* stc_allocate(int d, char c) {
  return stc_init(malloc(sizeof(stc)), d, c);
}

因此,这样做的好处是,您可以对init ed objets使用与其他变量相同的malloc函数。

另请注意,您的代码中存在错误,在C中,除非事先stc,否则struct除非typedef,否则无法使用{{1}}。

答案 2 :(得分:2)

第一种类型更容易发生内存泄漏。将记忆释放到malloc的位置是一种更好的做法。第二种方法看起来很整洁 并且void func(stc *stcP, int d, char c)执行初始化结构的预期任务。