elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Problema con punteros. Urgente: por favor.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con punteros. Urgente: por favor.  (Leído 1,629 veces)
chemaspain

Desconectado Desconectado

Mensajes: 9


Ver Perfil
Problema con punteros. Urgente: por favor.
« en: 28 Mayo 2011, 20:16 pm »

Tengo un problema con un puntero que me esta volviendo loco, hace lo que le da la gana, reserve o no memoria para el. Aqui dejo la estructura:

Código
  1. /*****************************************************************************
  2.          PRAC3
  3. ******************************************************************************/
  4.  
  5. #ifndef MARNET_H
  6. #define MARNET_H
  7.  
  8. /*****************************************************************************
  9.          Constants
  10. ******************************************************************************/
  11. #define MAX_SUPPLIERS   20
  12. #define MAX_CATEGORIES  5
  13. #define MAX_NAME        300
  14. #define MAX_PHONE       9
  15. #define MAX_SIZES       3
  16.  
  17.  
  18. /*****************************************************************************
  19.          TADs
  20. ******************************************************************************/
  21. typedef enum{white, pine, cherryTree, black} tColor;
  22. typedef enum{hall, dinningRoom, bedroom, ofice, kitchen, washroom} tCategoryName;
  23. typedef enum{cPending, inWarehouse, deliveredToClient} tCustState;
  24. typedef enum{sPending, received } tSupState;
  25.  
  26. typedef char tString[MAX_NAME+1];
  27.  
  28. typedef enum { FALSE, TRUE } bool;
  29.  
  30. typedef struct
  31. {
  32.        int day, month, year;
  33.        int hour, minutes;
  34. }tDate;
  35.  
  36. typedef struct tFurniture
  37. {
  38.        int idFurniture;
  39.        int idSup;
  40.        tString nameFur;
  41.        float sizes[MAX_SIZES];
  42.        tString typeFur;
  43.        tColor color;
  44.        float costPrice;
  45.        float retailPrice;
  46.        int deliveryTime;
  47.        struct tFurniture *prevFur, *nextFur;
  48.        struct tFurniture *prevFurType, *nextFurType;
  49. }tFurniture;
  50.  
  51. typedef struct tType
  52. {
  53.        tString typeName;
  54.        tFurniture *firstFur, *currFur;
  55.        struct tType *prevType, *nextType;
  56. } tType;
  57.  
  58. typedef struct
  59. {
  60.      tCategoryName catName;
  61.      tType *primType, *currType;
  62. } tCategory;
  63.  
  64. typedef struct
  65. {
  66.        int idSupplier;
  67.        tString name;
  68.        tString addr;
  69.        int phone[MAX_PHONE];
  70.        tFurniture *firstFur, *currFur;
  71.        float profitMargin;
  72. }tSupplier;
  73.  
  74. typedef struct tOrderRow
  75. {
  76.        int idProv;
  77.        int idFur;
  78.        int unit;
  79.        float unitCostPrice;
  80.        float profitMargin;
  81.        struct tOrderRow *nextOrderRow, *nextOrderRowSup;
  82. }tOrderRow;
  83.  
  84. typedef struct tCustomerOrder
  85. {
  86.        int idOrder;
  87.        tString nameCust;
  88.        tString addrCust;
  89.        int phoneCust[MAX_PHONE];
  90.        tDate createdDate;
  91.        tCustState state;
  92.        tOrderRow *firstItem, *currItem;
  93.        struct tCustomerOrder *nextCustOrder;
  94. }tCustomerOrder;
  95.  
  96. typedef struct tSupplierOrder
  97. {
  98.        int idOrder;
  99.        int idSupplier;
  100.        tDate createdDate;
  101.        tDate receivedDate;
  102.        tSupState state;
  103.        tOrderRow *firstItem, *currItem;
  104.        float totalPrice;
  105.        struct tSupplierOrder *nextSupOrder;                  
  106. }tSupplierOrder;
  107.  
  108. typedef struct
  109. {
  110.        tSupplier suppliers[MAX_SUPPLIERS];
  111.        int currSupplier, numSupplier;
  112.        tCategory categories[MAX_CATEGORIES];
  113.        tCustomerOrder *firstCustOrder, *currCustOrder;
  114.        tSupplierOrder *firstSupOrder, *currSupOrder;
  115. }tShop;
  116.  

Estas son las llamadas que me estan volviendo loco:

Código
  1. void cat_add_furniture (tCategory *c, tFurniture *f )
  2. {
  3.     tType *typeAux, *typeAux2;
  4.     tFurniture *furAux;
  5.  
  6.     typeAux = (tType*) malloc (sizeof(tType));
  7.     if (typeAux == NULL)
  8.     {
  9.                 printf("ERROR cat_add_furniture: not enough memory\n");
  10.                 f = NULL;
  11.                 return;
  12.     }
  13.  
  14.     furAux = (tFurniture*) malloc (sizeof(tFurniture));
  15.     if (furAux == NULL)
  16.     {
  17.                 printf("ERROR cat_add_furniture: not enough memory\n");
  18.                 f = NULL;
  19.                 return;
  20.     }
  21.  
  22.  
  23.   /* Buscamos en la lista tType bajo tCategory*/
  24.     typeAux = c->primType;
  25.  
  26.     while( (typeAux->nextType != NULL) && (typeAux->typeName != f->typeFur))
  27.     {
  28.            typeAux = typeAux->nextType;
  29.     }
  30.     /* Comprobamos si ya tenemos el tType en la lista, sino hemos de añadir un nuevo tType*/
  31.     if( typeAux->typeName == f->typeFur)
  32.     {
  33.         /* Ya tenemos el tipo en la lista, buscamos la posición donde insertar el nuevo mueble.
  34.          También comprobamos que el mueble no haya sido ya insertado.*/
  35.         furAux = typeAux->firstFur;
  36.         while(((furAux->nextFurType != NULL) && (f->idFurniture!=furAux->idFurniture)) || (f->retailPrice > furAux->retailPrice))
  37.         {                    
  38.                furAux = furAux->nextFurType;
  39.         }
  40.         if ( (furAux->idFurniture != f->idFurniture) || (f->retailPrice > furAux->retailPrice) )
  41.         {
  42.            /* Tenemos a furAux apuntando a la ultima posición de la lista o al mueble siguiente
  43.              ordenado por PVP. Añadimos el nuevo mueble, si no existe ya en la lista */
  44.            f->nextFurType = furAux->nextFurType;
  45.            f->prevFurType = furAux->prevFurType;
  46.            furAux->nextFurType = f;
  47.         }
  48.     }
  49.     else
  50.     {
  51.         /* No hemos encontrado el tipo y typeAux esta posicionado al final de la lista. Añadimos el nuevo tipo */
  52.         typeAux2 = (tType*) malloc (sizeof(tType));
  53.         if(typeAux2==NULL)
  54.         {
  55.             printf("ERROR cat_add_furniture: not enough memory\n");
  56.             f = NULL;
  57.             return;
  58.         }
  59.         typeAux->nextType = typeAux2;
  60.         strcpy(typeAux->typeName, f->typeFur);
  61.         typeAux2->prevType = typeAux;
  62.         typeAux2->nextType = NULL;
  63.         typeAux2->firstFur = f;
  64.         typeAux2->currFur = f;
  65.         f->nextFurType = NULL;
  66.         f->prevFurType = NULL;
  67.     }
  68.     free (typeAux);
  69.     free (typeAux2);
  70.     free (furAux);
  71. }
  72.  
  73. int sup_add_furniture(tShop *t)
  74. {
  75.    int i,idSup,idFur,delivery_time,numCat;
  76.    float margin,cost,retail_price,s[MAX_SIZES];
  77.    bool found;
  78.    tString name,type;
  79.    tColor color;
  80.  
  81.    margin = 0.0;
  82.  
  83.    /* Leemos los datos del mueble a añadir */
  84.    printf ("\nSupplier : ");
  85.    idSup = read_integer ();
  86.    idSup = idSup - 1;
  87.  
  88.    printf("\nFurniture id : ");
  89.    idFur = read_integer ();
  90.  
  91.    printf("\nFurniture Name : ");
  92.    read_string (name);
  93.  
  94.    printf("\nFurniture Type : ");
  95.    read_string (type);
  96.  
  97.    printf("\nFurniture width : ");
  98.    s[0]= read_real ();
  99.  
  100.    printf("\nFurniture Height : ");
  101.    s[1] = read_real ();
  102.  
  103.    printf("\nFurniture Depth : ");
  104.    s[2] = read_real ();
  105.  
  106.    printf("\nFurniture Colour : ");
  107.    color = read_colour ();
  108.  
  109.    printf("\nFurniture cost price : ");
  110.    cost = read_real();
  111.  
  112.    printf("\nFurniture Delivery time : ");
  113.    delivery_time = read_integer ();
  114.  
  115.    printf("\nHow many categories? ");
  116.    numCat = read_integer ();
  117.  
  118.    if (numCat>MAX_CATEGORIES)
  119.       numCat = MAX_CATEGORIES;
  120.  
  121.    tCategory cat[numCat];
  122.  
  123.    for (i=0;i<numCat;i++)
  124.    {
  125.        cat[i].catName = hall;
  126.        cat[i].primType = NULL;
  127.        cat[i].currType = NULL;
  128.    }
  129.  
  130.    for (i=0;i<numCat;i++)
  131.    {
  132.        printf("\nEnter a new Category (H:Hall D:diningroom  O:office K:Kitchen B:Bedroom W:Washroom): ");
  133.        cat[i].catName = read_category();
  134.        if (cat[i].catName == -1)
  135.        {
  136.              error ("sup_add_furniture: undefined category");
  137.              return cat[i].catName;              
  138.        }
  139.    }
  140.  
  141.    /* Buscar proveedor al cual tenemos que añadir el mueble. Si no existe acaba el programa con un mensaje de error */
  142.    if (search_supplier (*t,idSup) == -1)
  143.    {
  144.         error (ERROR_SUPPL_NOT_FOUND);
  145.         idSup = -1;
  146.         return idSup;
  147.    }
  148.  
  149.    /* Crear el objeto */
  150.    tFurniture *newFur = (tFurniture*) malloc (sizeof(tFurniture));
  151.    if(newFur==NULL)
  152.         {
  153.             printf("ERROR sup_add_furniture: not enough memory\n");
  154.             idSup= -1;
  155.             return idSup;
  156.         }
  157.    *newFur = newFurniture ();
  158.  
  159.    /* Actualizamos campos del objeto */
  160.    fur_set_idSupplier( newFur, idSup );
  161.    fur_set_id( newFur, idFur );
  162.    fur_set_name( newFur, name );
  163.    fur_set_color( newFur, color );
  164.    fur_set_costPrice( newFur, cost );
  165.    fur_set_deliveryTime(newFur, delivery_time );
  166.    fur_set_sizes( newFur, s );
  167.    fur_set_type( newFur, type );
  168.  
  169.    /* Calcular PVP del mueble : precio de coste + margen de beneficio del proveedor */
  170.  
  171.    if (idSup > -1) margin = sup_get_profitMargin (t->suppliers[idSup]);
  172.    margin = 1 + (margin / 100);
  173.    retail_price = cost * margin;
  174.    fur_set_retailPrice( newFur, retail_price );  
  175.  
  176.    /* Añadir el mueble, dentro de la estructura tShop, a las categorias y tipos correspondientes */
  177.  
  178.    for (i=0;i<numCat;i++)
  179.        cat_add_furniture (&cat[i], newFur );
  180.    if (newFur != NULL)
  181.       idSup = newFur->idSup;
  182.    else
  183.         idSup = -1;
  184.  
  185.    free (newFur);
  186.    return idSup;
  187. }
  188.  

En concreto en la funcion cat_add_furniture, a partir de las lineas donde esta el comentario, /* Buscamos en la lista tType bajo tCategory*/, parece como que no asigna el valor de c->primType a typeAux. Y he probado reservandole memoria y sin reservasela. El resultado siempre es el mismo, entra en el bucle del siguiente while aunque sea el primer registro que graba, y no debería ser así.

Alguien puede aportarme algo de luz al caso.

Gracias.

Saludos.
Chema.


En línea

dakomt

Desconectado Desconectado

Mensajes: 76


Viking Metal


Ver Perfil
Re: Problema con punteros. Urgente: por favor.
« Respuesta #1 en: 29 Mayo 2011, 17:28 pm »

Puf tal como planteas el problema esta dificil ayudarte... lo ideal aqui sería hacer una depuración linea por linea y hacer una trazabilidad de los punteros en cuestión.. Según comentas parece que c->primType entra con valor NULL a la función y por eso no se ejecuta el bucle no? pero claro.. sin saber de donde viene ese dato es imposible ayudarte xD

Mi consejo... que utilices un debugger... si viene incorporado en IDE que estés usando estupendo... si estás programando a pelo con un editor y compilando en consola pues agenciate alguno etc

Si no das con la tecla podrías postear el código entero en un zip indicando claramente donde reside el problema y a lo mejor alguna alma caritativa te ayuda


En línea

Akai


Desconectado Desconectado

Mensajes: 823



Ver Perfil
Re: Problema con punteros. Urgente: por favor.
« Respuesta #2 en: 29 Mayo 2011, 18:16 pm »

Esto es C o C++?

En cualquiercaso, NO puedes comparar cadenas así:

Código
  1. typeAux->typeName != f->typeFur

Tu tipo tString es un char[], que se compara carácter a carácter o usando strncmp().

Si hablásemos de c++ y strings SI lo podrías hacer. Pero como ya digo, en tu caso NO NO Y NO.

No me he parado a mirar otros errores más a fondo porque veo repeticiones de lo mismo
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
ayuda urgente por favor
Juegos y Consolas
vivastun 4 2,384 Último mensaje 3 Agosto 2004, 19:10 pm
por vivastun
Problema con Punteros en C
Programación C/C++
aaronas 8 3,729 Último mensaje 2 Abril 2012, 00:12 am
por david_BS
Problema con punteros.
Programación C/C++
vazquinhos 4 2,503 Último mensaje 20 Septiembre 2012, 18:35 pm
por do-while
Problema con punteros
Programación C/C++
NEGRO_PABLO 3 2,652 Último mensaje 30 Noviembre 2012, 18:41 pm
por twins
problema c++ codeblock por favor urgente
Programación C/C++
danielEE 2 1,481 Último mensaje 11 Diciembre 2016, 17:51 pm
por danielEE
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines