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?

Recommended Answers

All 3 Replies

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?

> 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.