2011-03-02 52 views
11

Quiero tener dos matrices en una estructura, que se inicializan al inicio pero necesitan editarse más adelante. Necesito tres instancias de la estructura, de modo que pueda indexar en una estructura específica y modificarla como desee. ¿Es posible?Matriz en C struct

Esto es lo que pensé que podía hacer pero me da errores:

struct potNumber{ 
    int array[20] = {[0 ... 19] = 10}; 
    char *theName[] = {"Half-and-Half", "Almond", "Rasberry", "Vanilla", …}; 
} aPot[3]; 

Entonces acceder a las estructuras de la siguiente manera:

printf("some statement %s", aPot[0].array[0]); 
aPot[0].theName[3]; 
… 
+6

¿Qué errores obtienes? –

+3

¿Así es como se define tu 'struct'? – birryree

Respuesta

11

La estructura mismos no tienen datos. Es necesario crear objetos del tipo de estructura y establecer los objetos ...

struct potNumber { 
    int array[20]; 
    char *theName[42]; 
}; 

/* I like to separate the type definition from the object creation */ 
struct potNumber aPot[3]; 
/* with a C99 compiler you can use 'designated initializers' */ 
struct potNumber bPot = {{[7] = 7, [3] = -12}, {[4] = "four", [6] = "six"}}; 

for (i = 0; i < 20; i++) { 
    aPot[0].array[i] = i; 
} 
aPot[0].theName[0] = "Half-and-Half"; 
aPot[0].theName[1] = "Almond"; 
aPot[0].theName[2] = "Rasberry"; 
aPot[0].theName[3] = "Vanilla"; 
/* ... */ 

for (i = 0; i < 20; i++) { 
    aPot[2].array[i] = 42 + i; 
} 
aPot[2].theName[0] = "Half-and-Half"; 
aPot[2].theName[1] = "Almond"; 
aPot[2].theName[2] = "Rasberry"; 
aPot[2].theName[3] = "Vanilla"; 
/* ... */ 
+0

No olvide que puede inicializar estructuras; disculpe el formato de mierda: struct potNumber aPot = {{[0] ... [19] = 10}, {"Mitad y mitad", "Almendra", "Rasberry", "Vainilla" .......}}; –

+0

@David: sí, excepto por el '...', eso funciona. Ejemplo agregado en mi fragmento de arriba. Gracias. – pmg

+0

@David: Esas son inicializaciones al estilo GCC (y dado que es Linux, supongo que es GCC). Sin embargo, nunca he visto las cosas de '......', ¿eso es válido? – birryree

9

En elementos de la matriz C struct debe tener un tamaño fijo, por lo que el char *theNames[] no es válido. Además, no puede inicializar una estructura de esa manera. En C, las matrices son estáticas, es decir, no se puede cambiar su tamaño de forma dinámica.

Una declaración correcta de la estructura es parecida a lo siguiente

struct potNumber{ 
    int array[20]; 
    char theName[10][20]; 
}; 

y inicializarlo como esto:

struct potNumber aPot[3]= 
{ 
    /* 0 */ 
    { 
     {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ }, 
     {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ } 
    }, 
    /* 1 */ 
    { 
     {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ }, 
     {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ } 
    }, 
    /* 2 */ 
    { 
     {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ }, 
     {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ } 
    } 
}; 

Pero, estoy bastante seguro de que esto no es lo que quiere. La forma más sana de hacer esto requiere algo de código repetitivo:

struct IntArray 
{ 
    size_t elements; 
    int *data; 
}; 

struct String 
{ 
    size_t length; 
    char *data; 
}; 

struct StringArray 
{ 
    size_t elements; 
    struct String *data; 
}; 
/* functions for convenient allocation, element access and copying of Arrays and Strings */ 

struct potNumber 
{ 
    struct IntArray array; 
    struct StringArray theNames; 
}; 

Personalmente me aconsejan el uso de matrices C desnudos. Hacer todo a través de estructuras y funciones auxiliares te mantiene alejado del almacenamiento intermedio/exceso excesivo y otros problemas. Cada codificador de C serio construye una biblioteca de código sustancial con cosas como esta a lo largo del tiempo.

+2

ok gracias por su ayuda, ¿podría darme un ejemplo de cómo ingresaría los datos y cómo podría acceder a ellos? – Greg