繁体   English   中英

结构体中数组的C Malloc

[英]C Malloc of array within a struct

我正在尝试使用main值分配一个结构。 我一直在寻找实现的方法,但是找不到答案。 我有3种硬币我想投入RET其价格的。 我如何申报RET从结构?

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

typedef struct
{

    double *ret;

}coin;


void ini(int a)
{
    ret = (double*)malloc(a*sizeof(double));
}


int main(void){

    long int a=250;
    int n_coins=3;


        coin *m = (coin*)malloc(n_coins*sizeof(coin));

        ini(a);

        m[0].ret[0] = 2000;
        printf("%lf", m[0].ret[0]);



    return 0;
}

首先, return是C中的保留keyword ,您不能将保留关键字用作变量名。

其次,如果要在其他函数中为任何数据类型的数组分配内存,则在该函数中声明一个变量,调用malloc ,通过malloc分配所需的空间并返回已分配空间的第一个元素的地址。返回被调用函数(这里的main() )不知道分配的空间的地址,并且它无法访问分配的内存空间。您可以这样执行:

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

typedef struct
{
   double *var;
}moeda;


double *ini(int n)
{
   double *arr;
   arr = malloc(n*sizeof(*arr));
   return arr;
}

int main(void){

   long int a=250;

    moeda m;

    m.var=ini(a);

    m.var[0] = 2000;
    printf("%lf", m.var[0]);



    return 0;
}

如果我有您的代码并必须对其进行改进,我会争取

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

// The kernel style guide https://www.kernel.org/doc/html/v4.10/process/coding-style.html discourages typedefs for structs
typedef struct moeda {
    double *return_value;
} moeda;


// return a struct here:
moeda initialize_return(int a)
{
    moeda ret;
    ret.return_value = malloc(a*sizeof(double));
    return ret;
}


int main(void) {
    long int a=250;

    moeda m = initialize_return(a);

    m.return_value[0] = 2000;
    printf("%lf", m.return_value[0]);

    return 0;
}

(最好将所有标识符都用英语表示)。

这将是第一步。 然后我可能会意识到并不需要该结构,并替换它:

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

double * initialize_double_array(int a)
{
    return malloc(a*sizeof(double));
}

int main(void) {
    long int a=250;

    double * arr = initialize_double_array(a);

    arr[0] = 2000;
    printf("%lf", arr[0]);

    return 0;
}

OTOH,如果在所述结构中还有其他字段,我可能会决定是否应该将它们与该数组一起初始化。

一些变体:

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

// The kernel style guide https://www.kernel.org/doc/html/v4.10/process/coding-style.html discourages typedefs for structs
struct moeda {
    int num_values;
    double *values;
};

// only fill a struct here:
// i. e. take a pre-initialized struct and work with it:
void moeda_alloc_values(struct moeda * data) 
{
    data->return_value = malloc(data->num_values * sizeof(double));
}

// return a struct here:
struct moeda initialize_moeda(int num) 
{
    struct moeda ret;
    ret.num_values = num;
    ret.return_value = malloc(num * sizeof(double));
    // or just moeda_alloc_values(&ret);
    return ret;
}

int main(void) {
    long int a=250;

    struct moeda m = initialize_return(a);
    m.return_value[0] = 2000;
    printf("%lf", m.return_value[0]);

    struct moeda m2;
    m2.num_values = 20;
    moeda_alloc_values(&m2);
    m2.return_value[0] = 2000;
    printf("%lf", m2.return_value[0]);

    return 0;
}

struct返回函数的优点是返回后具有“立即填充”的结构。

另一个通过指针修改结构的函数的优点是,它可以在任何可能预先填充的,可能已分配的结构上工作,并且可以在单个字段上工作,而不必考虑所有字段。

return是c中的关键字。 您不能将其用作变量名。 我也不清楚这个问题。 什么是“ moeda m”? 萌达在这里? 如果这不是英语C,我很抱歉。

我假设您只是意味着您正在尝试从main中调用的函数向结构分配内存。 为了清楚起见,我更改了您的变量名。 因此,首先,正如其他人所说,您不能将return用作变量名。 我还建议您使用结构的大小,而不是仅使用两倍,因为将来您在结构中可能会有多个变量。

如果要使用main函数,则必须将指针传递给该函数,然后使用malloc为该函数分配内存,然后返回它。 或者,您可以将struct指针设置为全局选项。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "stdafx.h"
#include <malloc.h>

typedef struct
{
    double number;
}example;

example *allocateMemory(int a, example *s)
{
    s = (example*)malloc(a * sizeof(example));
    return s;
}

int main() {

    long int a = 250;
    example *structure = NULL;
    structure = allocateMemory(a, structure);

    structure[0].number = 2000;

    printf("%lf\n", structure[0].number);

    //cleaning up memory
    free(structure);
    structure = NULL;
    return 0;
}

只是其他一些说明,我让我的示例结构等于null,因为编译器抱怨未初始化的局部变量。

在您的代码中,您有这个。

m.retorno[0] = 2000;

但我假设您想访问struct数组中的第一个数字,因此应该是:

structure[0].number = 2000;

对于此特定示例,我将执行以下操作:

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

typedef struct
{
   size_t  nLen;    // number of elements allocated for var
   double *var;     // pointer to a list of double variables
} moeda;

// struct is small so just initialize the whole thing and return it
// from the initialization routine.
moeda iniMoeda (size_t n)
{
   moeda x = {0};

   x.var = malloc(n * sizeof(double));   // try to allocate the requested number of doubles
   if (x.var) x.nLen = n;     // if allocated then remember number of doubles

   return x;
}

// free a moeda variable. we require a pointer so that we can reset
// the moeda variable to a known state of NULL pointer and zero allocation
// length so that we can easily catch using the variable after the memory
// has been freed. Hope for Address exception on a NULL pointer if this
// variable is used after freeing.
void freeMoeda (moeda *x)
{
    // free the allocated doubles and clear everything.
    // if x->var is NULL then free() does nothing.
    free (x->var); x->var = NULL; x->nLen = 0;
}

int main(void)
{
    size_t  a = 250;
    moeda   m = iniMoeda (a);

    if (m.var) {
        // allocation worked so lets test our space
        m.var[0] = 2000;
        printf("%lf", m.var[0]);
    } else {
        printf ("m.var is NULL.\n");
    }

    freeMoeda (&m);
    return 0;
}

以下建议的代码:

  1. 干净地编译
  2. 说明为什么包含每个头文件
  3. 执行所需的操作
  4. 自我清理后
  5. 包含有关代码中每个步骤的嵌入式注释

注意:代码必须一致,可读并执行所需的功能

现在,建议的代码:

// for ease of readability and understanding:
// 1) insert a space:
//    after commas,
//    after semicolons,
//    inside brackets,
//    inside parens,
//    around C operators
// 2) separate code blocks
//    ( 'for' 'if' 'else' 'while' 'do...while' 'switch' 'case' 'default' )
//    via a single blank line
// 3) variable (and parameter) names should indicate
//    'content' or 'usage' (or better, both)

#include <stdio.h>   // printf(), perror()
#include <stdlib.h>  // malloc(), free(), exit(), EXIT_FAILURE
// do not include header files those contents are not used
//#include <math.h>
//#include <string.h>

// added 'sCOIN' tag name to make it easier to use debugger
// since most debuggers use the tag name to reference fields inside a struct
typedef struct  sCOIN
{
    double *ret;
} coin;


int main( void )
{
    // 'malloc()' expects its parameters to be of type 'size_t'
    size_t n_coins=3;
    coin  mycoin;

    // do not cast the returned value from 'malloc()', 'calloc()', 'realloc()'
    // as the returned type is 'void*' which can be assigned to any pointer
    //coin *m = (coin*)malloc(n_coins*sizeof(coin));
    mycoin.ret = malloc( n_coins * sizeof( double ) );
    // always check to assure the operation was successful
    if( !mycoin.ret )
    {
        // 'perror()' outputs the enclosed text
        // and the text of why the system thinks the error occurred
        // to 'stderr'
        perror( "malloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    // the field in 'coin' is declared a DOUBLE so assign a double
    // not a integer.  I.E include a decimal point '.'
    mycoin.ret[ 0 ] = 2000.0;
    printf( "%lf", mycoin.ret[ 0 ] );

    // code should always clean up after itself
    // I.E. don't leave a mess nor depend on the OS to cleanup.
    free( mycoin.ret );
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM