Converting a vectorstruct in C ++ in C

1

I'm trying to adapt a C ++ function in pure C. I changed the names of the variables and structs because it is not the case.

typedef struct struct1 {
    int a;
    int b;
    int c;
    string d;
} STRUCT1;

typedef struct struct2 {
    int aa;
    int bb;
    int cc;
    clock_t time;
} STRUCT2;

vector<STRUCT2> createVector(STRUCT1 str1) 
{
    vector<STRUCT2> vec;
    int var = str1.c, count = 0;
    for (int i = 0; i < str1.b; i++) {
        usleep(1);
        STRUCT2 aux;
        aux.aa = 0;
        aux.bb = count;
        aux.cc = 0;
        aux.time = clock();//start times
        vec.push_back(aux);
        if (--var == 0) {
            var = str1.c;
            count++;
        }
    }
return vec;
}

My questions are:

  • vector<STRUCT2> createVector(STRUCT1 str1)
  • vector<STRUCT2> vec;
  • vec.push_back(aux);
  • How would I pass these 3 lines of code to pure C in the above code?

        
    asked by anonymous 18.11.2016 / 00:44

    2 answers

    2

    With a lot of work. At least if you're going to do it all. In practice you will have to create your own vector , which is not something simple. You even have a naive implementation, but it will not do close to vector . You'll have to use realloc() , but do not just use the function. To have the same semantics is complicated. If you can change the semantics there may be easier, but the question does not say anything about it.

    You even have a example in the SO , but found the implementation pretty bad.

    You can use a library that has this ready. By suggestion from Anthony Accioly can use GLib or Gnulib .

    To understand the problem, read What prevents an array from being booted with a variable length in C? .

        
    18.11.2016 / 01:01
    0

    Because C does not have containers like std::vector , the way is to use a dynamically allocated array.

    STRUCT2 *createVector(STRUCT1 str1) 
    {
        STRUCT2 *vec = malloc(str1.b * (sizeof vec));
        int var = str1.c, count = 0;
        for (int i = 0; i < str1.b; i++) {
            usleep(1);
            STRUCT2 aux;
            aux.aa = 0;
            aux.bb = count;
            aux.cc = 0;
            aux.time = clock();//start times
            vec[i] = aux;
            if (--var == 0) {
                var = str1.c;
                count++;
            }
        }
        return vec;
    }
    
        
    18.11.2016 / 00:56