Saltar al contenido principal
LibreTexts Español

12.4: Uso de la memoria

  • Page ID
    82110
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    El puntero que se devuelve desde la función de asignación se utiliza como base del objeto o matriz de objetos en los que te interese. Manteniéndolo simple, supongamos que desea asignar una matriz de tres enteros. Si desea establecer el primer elemento en 0, y el segundo y tercer elementos en 1, haga lo siguiente (solo fragmento de código, no se muestra el procesamiento de errores):

    int *ip;
    
    if( ip = calloc( 3, sizeof(int) ) )
    {
        *ip = 0;
        *(ip+1) = 1;    /* could also say ip[1] = 1; */
        *(ip+2) = 1;    /* could also say ip[2] = 1; */
    }
    

    Anote la libertad que tenemos con el puntero. Se puede usar como un puntero normal o pensarse como la base de una matriz e indexarse en consecuencia. Del mismo modo, podríamos necesitar asignar una estructura e inicializar sus campos. Aquí hay una función a la que podemos llamar para asignar una estructura foobar, inicializar algunos campos y devolverle un puntero.

    struct foobar {
        double d;
        int i;
        char name[20];
    };
    
    /* other code... */
    
    struct foobar * alloc_foobar( void )
    {
        struct foobar *fp;
        
        if( fp = malloc( sizeof(struct foobar) ) )
        {
            fp->d = 12.0; /* just some stuff to show how... */
            fp->i = 17;
            strcpy( fp->name, “Timmy” );
        }
        return( fp );
    }
    

    This page titled 12.4: Uso de la memoria is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by James M. Fiore via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.