gpt4 book ai didi

c - 返回一个大变量与使用参数中提供的指针设置它

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:40 25 4
gpt4 key购买 nike

我对设置或返回 C 函数内部生成的大型结构时的常见做法很感兴趣。最好和最安全的方法是什么。我可以想出 3 种返回生成结构的方式。他们是否都在明智地执行相同的 Action ,或者一个比另一个更有效?覆盖现有值时事情会发生变化吗?例如,当一个指针发生变化时,旧的关联值会自动被垃圾回收。

// 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. 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. Image *new_Image(Image *out, const int height, const int width, const int depth) 如果您使用在函数外部定义或分配的对象,则安全。顺便说一句,你忘了返回指针。

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

    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 系列函数的结果。它被认为是危险的,因为如果您忘记包含,使用所有标准的语言您将不会收到任何警告消息。如今,如果您在没有原型(prototype)的情况下调用函数,编译器会发出警告

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

关于c - 返回一个大变量与使用参数中提供的指针设置它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56715093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com