Converting a vector<struct> to C++ into C

Asked

Viewed 163 times

1

I am trying to adapt a C++ function into pure C. I have changed the variable names and structs because it’s beside the point.

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 doubts are:

  1. vector<STRUCT2> createVector(STRUCT1 str1)
  2. vector<STRUCT2> vec;
  3. vec.push_back(aux);

How I would pass these 3 lines of code to pure C in the above code?

2 answers

2


With a lot of work. At least if you do everything by hand. In practice you will have to create your own vector, which is not something simple. It even has how to make a naive implementation, but it will not even do the same thing as the vector. You will have to use the realloc(), but not just using the function. To have the same semantics is complicated. If you can change the semantics then it can get easier, but the question says nothing about it.

There’s even a example in the OS, but I found the implementation very bad.

You can use a library that has it ready. By suggestion by Anthony Accioly can use the Glib or Gnulib.

To understand the problem read This prevents an array from being initialized with a variable size in C?.

0

As C does not have containers like the 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;
}
  • Emoon, I used this format and it worked... (in parts) I’m having trouble printing this vector returned... example:

  • @Oberdansantos I’m sorry to reject your edition, but it significantly altered the answer, even if it is only one * Plus. If this was a silly little mistake about something Emoon forgot, then everything would be fine. But it turns out, at least in my opinion, the code should not compile with the * and the way that Emoon left it should be right. Cases like this would be best solved through conversations in comments.

  • @Victorstafusa Quiet, got it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.