返回大变量与使用参数中提供的指针进行设置

时间:2019-06-22 11:29:43

标签: c pointers return

我对设置或返回C函数内部生成的大型结构时常见的做法感兴趣。最好和最安全的方法是这样做。我可以提出三种返回生成的结构的方式。它们是否都在记忆上执行相同的动作,还是效率更高?覆盖现有值时情况会发生变化吗?例如,当更改一个指针时,旧的关联值会自动收集垃圾。

// Returning the instance

Image new_Image(const int height, const int width, const int depth) {
   Image out;
   out.width = width;
   out.height = height;
   out.depth = depth;
   out.pixels = (float*) calloc((height*width*depth), sizeof(float));
   return out;
}

Image image = new_Image(100,100,3);

// OR return a new pointer.

Image *new_Image(const int height, const int width, const int depth) {
   Image out;
   out.width = width;
   out.height = height;
   out.depth = depth;
   out.pixels = (float*) calloc((height*width*depth), sizeof(float));
   return &out;
}

Image *image;
image = new_Image(100,100,3);

// OR init outside function and populate in function. For cleanliness though I'd like as much of the image generating part to be done in the function. 

Image *new_Image(Image *out, const int height, const int width, const int depth) {
   out.width = width;
   out.height = height;
   out.depth = depth;
   out.pixels = (float*) calloc((height*width*depth), sizeof(float));
}

Image *image = (Image*) malloc(sizeof(Image));
new_Image(image, 100,100,3);

1 个答案:

答案 0 :(得分:1)

  1. Image new_Image(const int height, const int width, const int depth)

很安全,但是您可以通过值返回整个结构-这不是很有效,大多数实现将通过堆栈来完成。特别是在小型嵌入式系统上,堆栈的大小非常有限。也不友好递归(每个函数调用消耗大量堆栈)

  1. Image *new_Image(const int height, const int width, const int depth) { Image out;-将指针返回到局部变量时未定义的行为,当您离开该函数时该变量不再存在。

  2. 如果使用在函数外部定义或分配的对象,则
  3. Image *new_Image(Image *out, const int height, const int width, const int depth)是安全的。顺便说一句,您忘记了返回指针。

  4. 您在问题中未提及的选项:

    Image *new_Image(const int height, const int width, const int depth) {
       Image *out = malloc(sizeof(*out));
       /* malloc result tests */
       out -> width = width;
       out -> height = height;
       out -> depth = depth;
       out -> pixels = calloc((height*width*depth), sizeof(float));
       /* calloc result tests */
       return out;
    }

您不测试内存分配结果。它必须完成。

此功能也是错误的:

Image *new_Image(Image *out, const int height, const int width, const int depth) {
   out.width = width;
   out.height = height;
   out.depth = depth;
   out.pixels = (float*) calloc((height*width*depth), sizeof(float));
}

应该是:

Image *new_Image(Image *out, const int height, const int width, const int depth) {
   out -> width = width;
   out -> height = height;
   out -> depth = depth;
   out -> pixels = calloc((height*width*depth), sizeof(float));
   return out;
}

您不需要强制转换malloc系列函数的结果。这被认为是危险的,因为使用所有标准语言,如果您忘记包含该语言,则不会收到任何警告消息。如今,如果您在没有原型的情况下调用函数,编译器会发出警告

如果您使用C ++编译器编译代码,请使用命令行选项,该选项将告诉编译器代码是C(例如gcc或g ++ -xc选项)

相关问题