Search code examples
cdynamic-arrays

Flexible array in C


Im trying to have an unlimited array in C to store some data. My header file stock.h looks like this

#ifndef STOCK_H
#define STOCK_H

typedef struct {
    char* id;
    char* descripcion;
    int precio;
} tAppliance;

typedef struct {
    int cantidad;
    tAppliance electrodomestico;
} tElectroStock;

typedef struct {
    int size;
    int capacity;
    tElectroStock *electrodomesticos;
} tStock;

void tstock_init(tStock *stock);

void tstock_add(tStock *stock, tAppliance item, int cantidad);

#endif

My stock.c file

#include <stdio.h>
#include "stock.h"

void tstock_init(tStock *stock) {
    stock->size = 0;
    stock->capacity = 10;
    stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
}

void tstock_add(tStock *stock, tAppliance item, int cantidad) {
    if(stock->size >= stock->capacity) {
        stock->capacity = stock->capacity * 2;
        stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
    }
    tElectroStock t;
    t.cantidad = cantidad;
    t.electrodomestico = item;
    stock->size++;
    stock->electrodomesticos[stock->size] = t;  
}

And finally my main function

#include <stdio.h>
#include "stock.h"

int main(int argc, char **argv)
{
    tStock t; // Creamos nuestra variable de stock
    tstock_init(&t); // Iniciamos el stock
    tAppliance item;
    item.descripcion = "Television SONY";
    item.id = "apeid9";
    item.precio = 20;
    tstock_add(&t, item, 1);
    tstock_add(&t, item, 1);
}

As you can see on my main function I try to add 2 items to tStock. however adding the second item seems to crash the whole applicattion and no idea why.


Solution

  • Enable all warnings, and treat every single one of them as error. That way you could've found the issue with the member not being a pointer that's already been mentioned yourself.

    Check the return value of library functions like malloc and realloc for errors and handle them appropriately.

    Finally, you'll want to swap these two lines:

    stock->size++;
    stock->electrodomesticos[stock->size] = t;