Hi

I have encountered a problem using vectors. I have a vector<char*> in a for loop, adding a char* to it after each iteration, but when I exit the loop and run through the contents of the vector, it has 4 copies of the final char* added.

Here is the code:

std::vector<char*> tempC;
char *c = new char[107];
    c[106] = '\0';
    tempC.clear();

    for (int i = 0; i < 4; i++)
    {      
        s = randomString(14) + ha + randomString(11);

        stringToMpuint(s, xm);
        EncryptDecrypt(ym, xm, d, n);

        mpuintToChar(c, ym);
        tempC.push_back(c);
    }

I have checked the value of c before adding it to the vector and it is correct.
Does anyone know why this is happening?

So stop wasting your time and use a std::string instead.

> Does anyone know why this is happening?
How many char* pointers do you actually ALLOCATE?

Is it four?

So stop wasting your time and use a std::string instead.


> Does anyone know why this is happening?
How many char* pointers do you actually ALLOCATE?

Is it four?

I need it in a char* to send through a TCP socket to a server.

This has fixed things, I moved the declaration of the char* c inside the for loop.

I was under the impression though that a vector makes a copy of the char* and stores it?

Edited 6 Years Ago by macdougc: n/a

> Does anyone know why this is happening?
Erm, nope.
When you actually get to the point of sending to the TCP server, you use the c_str() method on the string.

Until you ABSOLUTELY need to communicate with some legacy interface, there is no reason to mess about with char pointers.

> I was under the impression though that a vector makes a copy of the char* and stores it?
Yeah, copy of the POINTER.
Not what it points at.

This article has been dead for over six months. Start a new discussion instead.