2
I’m having problems printing vector structs in C, in C++ it worked...
First I will show the version in C with problems (in the execution because compiles without errors)
CACHE cache = createCache(descricao); //chamada da main
printaCache(cache); //chamada da main
Now the functions:
CACHE createCache(CACHEDESC desc)
{
    int i, associatividade, contador=0;
    CACHE *vec;
    vec = malloc(desc.number_of_lines * (sizeof vec));
    associatividade = desc.associativity, contador = 0;
    for (i = 0; i < desc.number_of_lines; i++) {
        CACHE auxiliar;
        auxiliar.tag = 0;
        auxiliar.index = contador;
        auxiliar.data = 0;
        auxiliar.time = clock();//start times
        vec[i] = auxiliar;
        --associatividade;
        if (associatividade == 0)
        {
            associatividade = desc.associativity;
            contador++;
        }
    }
    return *vec;
}
void printaCache(CACHE vec)
{
    int i;
    for(i=0;i<sizeof(vec);i++)
    {
         printf("%d \t %d \t %d \t %d\n",i, vec);
    }
}
These functions compile without errors or warnings, but when running the program it crashes...
The C++ code that works 100% is:
void printCache(vector<CACHE> cache){
    for(int i=0; i<cache.size(); i++){
        cout<< i<< "\t "<< cache[i].tag << " \t " << cache[i].index <<"\t "<< cache[i].time  << "\n";
    }
 } 
vector<CACHE> createCache(CACHECONFIG conf){
    vector<CACHE> vec;
    int assoc = conf.associativity, count=0;
    for(int i=0; i<conf.numLines; i++){
        CACHE aux;
        aux.valido=true;
        aux.tag=0;
        aux.index=count;
        aux.dado=0;
        aux.time = clock();//inicio dos tempos
        vec.push_back(aux);
        if(--assoc==0){
            assoc=conf.associativity;
            count++;
             } 
        }
        printCache(vec);
        return vec;
    }
Both languages are using structs:
typedef struct cache{
    int tag;
    int index;
    int dado;
    clock_t time;
}CACHE;
Anyway, I’d like to know what I’m missing in code C so I don’t get the same result as code C++
I would tell you not to invent the wheel. If the program needs to be in C use the Glib (see
GArray) or Gnulib, [see that mobile). Implementing nail collections for a real program (as opposed to an exercise) quickly becomes a difficult task.– Anthony Accioly