I'm working on some data structures in C++ and I'm having trouble understanding some problems with the char * data type. I've worked with C++ before, but I've always used the std::string class to handle string data. I'm trying to avoid that in this project--to improve performance, but also so I can really understand how to use char *.
In Feature.h, I have this constructor.
Feature(char * data);
Elsewhere, I am trying to instantiate a Feature object with this code.
1 2 3 4 5 6 7 8 9 10 11 12
int initial_index = bufferindex;
char c = buffer[bufferindex];
while(c != '\n' && bufferindex < bufferlength)
{
bufferindex++;
}
int length = bufferindex - linepos;
char line [length];
strncpy(line, buffer + initial_index, length);
bufferindex++;
Feature nextFeature (line);
However, when I try to compile, I get this error.
error: no match for call to ‘(Feature) (char [(((longunsignedint)(((int)length) - 1)) + 1u)]’
Most compilers do not allow variable length arrays because it is non-standard.
(GCC allows it as an extension).
char line[ length ];
length must be declared const for this to work.
BTW, the only difference I see in your above code vs. std::string is you are using fixed-length
stack-based arrays of chars as opposed to letting string manage the memory for you. You
probably could eliminate any performance issues by sizing your strings at instantiation time.
This means only one allocation per string.