0

I have an array char buffer[]. What I want to do, is to copy values from buffer from foundSecondComma+1 to foundSecondComma+1+dataLen.

Next, I want to creat object Answer a and pass to constructor few data with part of buffer.

// here extracted buffer will be stored
char contentData[dataLen];

// extract data from buffer
copy(buffer + foundSecondComma+1, buffer+foundSecondComma+1+dataLen, contentData);

//create new object and push to list
Answer a(dataLen, header, contentData);
answers.push_back(a);

And this is my Answer class:

Answer::Answer(int dataLen, string header, char* content) {
    this->dataLen = dataLen;
    this->header = header;

    this->content = new char[strlen(content)+1];
    strcpy(this->content, content);
}

So for some reason a.content stores different data than part of buffer. This simple loop:

for(int i=0; i<v.dataLen; i++)
{
    printf("buffer[%d]=%c  a.content[%d]=%c\n", i, buffer[foundSecondComma+1+i], i, a.content[i]);
}

Is showing, that values are not the same. Where I make mistake? I am using g++ to compile program.

dafi
  • 1
  • 2
  • From the context, I assume that `dataLen` is not a compile time constant. In that case, `char contentData[dataLen];` is not standard c++. It uses an extension known as variable length arrays. Some compilers like gcc support it by default, but it's not portable. – François Andrieux Jan 24 '18 at 19:42
  • @FrançoisAndrieux I've read that I can use this in `g++`: https://stackoverflow.com/a/15013295/9249024 – dafi Jan 24 '18 at 19:43
  • It's not wrong to use them, but you should prefer portable alternatives such as `std::vector`. Though on Stack Overflow, unless otherwise specified, c++ code is expected to be standard conforming. – François Andrieux Jan 24 '18 at 19:44
  • 1
    It seems unlikely that `contentData` is null terminated, meaning it wouldn't be a string. Passing it to `strcpy` would be undefined behavior. – François Andrieux Jan 24 '18 at 19:45
  • Could you put the declarations for the member variables of your Answer class? – Onur A. Jan 24 '18 at 22:18

0 Answers0