gpt4 book ai didi

c++ - 函数内部数组的动态分配

转载 作者:行者123 更新时间:2023-11-30 17:25:45 24 4
gpt4 key购买 nike

我正在尝试 malloc 并初始化一个数组,然后通过传入的指针将其返回给调用函数。 (g++)

例如:

float* buff;
allocateBuff(&buff);
buff[0] = 2.3;
free(buff);

int allocateBuff(float** buffer)
{
*buffer = (float*) malloc(sizeof(float)*1);

return 0;
}

但是,这个段出现了错误。

最佳答案

您的函数返回必须与您希望返回的指针类型匹配。如果您想分配一个 float 数组,那么您的函数必须是 float * 类型。以下是一个简单的示例:

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

float *allocateBuff(float** buffer, int size)
{
/* allocate array of floats */
*buffer = calloc(size, sizeof(*buffer));

return *buffer;
}

int main() {

float *array = NULL;
array = allocateBuff (&array, 10);

int i;

for (i = 0 ; i < 10; i++)
array[i] = (float)i;

for (i = 0 ; i < 10; i++)
printf ("array [%d] : %f\n", i, array[i]);

if (array) free (array);

return 0;
}

输出:

$ ./bin/initfloat
array [0] : 0.000000
array [1] : 1.000000
array [2] : 2.000000
array [3] : 3.000000
array [4] : 4.000000
array [5] : 5.000000
array [6] : 6.000000
array [7] : 7.000000
array [8] : 8.000000
array [9] : 9.000000
<小时/>

此外,根本不需要将 buffer 传递给函数。您可以轻松地定义您的函数:

float *allocateBuff (int size)
{
/* allocate array of floats */
float *buffer = calloc (size, sizeof(*buffer));

return buffer;
}

然后在代码中初始化数组:

float *array = NULL;
array = allocateBuff (10);

关于c++ - 函数内部数组的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26988790/

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