Saltar al contenido principal
LibreTexts Español

10.3: Estructuras, matrices, etc.

  • Page ID
    82384
  • \( \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}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    Hemos visto que es posible tener matrices dentro de las estructuras. También es posible tener estructuras dentro de las estructuras y punteros dentro de las estructuras. Aquí hay algunos ejemplos:

    /* The structure definitions */
    struct foo {
        float x;
        float y;
    };
    
    struct bar {
        double *pd;
        struct foo littlefoo;
        struct foo *pf;
    };
    
    /* The variable declarations */
    struct foo my_foo;
    struct bar my_bar;
    struct bar *pbar = &my_bar;
    double z=1.0;
    

    La estructura de barras contiene un puntero a un doble, un puntero para struct foo y un struct foo. Accederíamos a ellos de la siguiente manera:

    my_bar.pd = &z; /* pd isn’t a double but the address of one, hence & */
    my_bar.littlefoo.x = 2.2;
    pbar->littlefoo.y = 3.3;
    pbar->pf = &my_foo;
    pbar->pf->x = 4.4;
    

    Ten en cuenta que si no dijiste pbar->pf = &my_foo; primero, entonces pbar->pf->x = 4.4; ¡sería muy malvado! Sin asignar my_foo a pf, este puntero contendría algún número aleatorio. La segunda sentencia usaría entonces ese número como dirección de inicio de struct foo, y escribiría el número 4.4 donde debería estar el campo x. Como es muy poco probable que este número aleatorio sea la dirección de inicio de una struct foo, el número 4.4 sobrescribe otra cosa. Eso podría significar que otros datos o incluso código se destruyen. Tu programa se comporta de manera errática o se bloquea.

    Regla de puntero número uno

    ¡Nunca desreferencia 1 a un puntero no inicializado!

    Solo pasarán cosas malas, malas y te convertirás en un programador muy triste.

    Al inicio del ejemplo de transistores notamos que podríamos querer crear un montón de transistores. Una posibilidad es usar una matriz. Hay otras formas, como veremos. Así es como declararía una matriz de 1000 estructuras de transistores, dada la definición anterior:

    struct transistor transistors[1000];
    

    Accedería al campo de la siguiente manera:

    transistors[0].currentgain = 200.0; /* set 1st device’s gain to 200 */
    transistors[2].breakdown = 85.0; /* set 3rd device’s breakdown to 85 */
    

    Finalmente, también es posible crear una matriz de punteros para estructuras de transistores:

    struct transistor *ptarray[1000];
    

    Tenga en cuenta que no tenemos 1000 estructuras de transistores, sino 1000 punteros. Cada uno de estos tendría que apuntar a una estructura de transistor apropiada. Asumiendo que has declarado uno llamado my_transistor como lo hicimos antes, podrías escribir:

    ptarray[0] = &my_transistor;
    

    Y podrías acceder a campos así:

    ptarray[0]->maxpower = 25.0;
    

    Aunque esto puede parecer un poco extraño al principio, este tipo de construcción tiene algunos buenos usos en aplicaciones más avanzadas. Para estirar tu mente un poco más lejos, C hace posible crear algo así como una matriz de punteros a estructuras que contienen una estructura que a su vez contiene una matriz de punteros a otras estructuras. Lee eso de nuevo, imagina cómo podría ser eso como un mapa de memoria, y luego escribe algunas posibles definiciones/declaraciones. Si puedes hacer eso, has dominado bastante bien la idea.


    1. es decir, tratar de acceder a los campos de.

    This page titled 10.3: Estructuras, matrices, etc. 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.